【发布时间】:2021-10-15 11:20:08
【问题描述】:
我试图将 tempdata 与 ip 地址一起使用,当我尝试将 tempdata 分配给 ipaddress 变量时,它说我需要对其进行序列化,所以我在网上看到了如何序列化 ip 地址变量。在实现它之后,我在中间件中遇到了一个问题,我在其中创建了一个变量IPAddress ipAddress,并在我的 tempdata.containskey() 的 if 语句中将其分配为 `ipAddress = (IPAddress)tempdata.Peek("ipaddress")。 ToString();但是在调试时我看到它给了我一个异常说:
System.InvalidCastException:无法将“System.String”类型的对象转换为“System.Net.IPAddress”类型
然后我将 IPAddress ipAddress 更改为 string ipAddress,现在当它在 tempdata 的 if 语句中遇到 ipAddress 时 ipAddress 将保持 "\"::1\"" .现在是因为我正在调试它而用两个“\”'显示它吗?它真的拥有“::1”的价值吗?只是想确保我没有让 ipAddress 使用两个 \'s 来保存这样的值。
Middleware:
public class CorrelationIdMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger _logger;
private readonly ITempDataDictionaryFactory _tempDataDictionaryFactory;
public CorrelationIdMiddleware(RequestDelegate next, ILoggerFactory loggerFactory, ITempDataDictionaryFactory tempDataDictionaryFactory)
{
_next = next;
_logger = loggerFactory.CreateLogger<CorrelationIdMiddleware>();
_tempDataDictionaryFactory = tempDataDictionaryFactory;
}
public async Task Invoke(HttpContext context)
{
string correlationId = null;
string userName;
string ipAddress;
var tempData = _tempDataDictionaryFactory.GetTempData(context);
var key = context.Request.Headers.Keys.FirstOrDefault(n => n.ToLower().Equals("x-correlation-id"));
if (!string.IsNullOrWhiteSpace(key))
{
correlationId = context.Request.Headers[key];
_logger.LogInformation("Header contained CorrelationId: {@CorrelationId}", correlationId);
}
else
{
if (tempData.ContainsKey("username") && tempData.ContainsKey("ipaddress"))
{
userName = tempData.Peek("username").ToString();
ipAddress = tempData.Peek("ipaddress").ToString();
context.Response.Headers.Append("X-username", userName);
context.Response.Headers.Append("X-ipAddress", ipAddress);
}
correlationId = Guid.NewGuid().ToString();
_logger.LogInformation("Generated new CorrelationId: {@CorrelationId}", correlationId);
}
context.Response.Headers.Append("x-correlation-id", correlationId);
using (LogContext.PushProperty("CorrelationId", correlationId))
{
await _next.Invoke(context);
}
}
}
【问题讨论】:
标签: c# html asp.net-core-mvc ip-address tempdata