gpt4 book ai didi

azure - DNX(rc1-最终版): IHttpConnectionFeature not found

转载 作者:行者123 更新时间:2023-12-02 07:30:20 24 4
gpt4 key购买 nike

使用最新的 ASP.NET 5 rc1-final 版本,我尝试在 Azure API 应用程序 Controller 方法内查找远程 IP 地址。

运行代码时,“上下文”是 Controller 方法内的 this.HttpContext。

但是该功能将返回 null,因为该功能不存在。

    IHttpConnectionFeature feature = context.Features.Get<IHttpConnectionFeature>();

是否必须在配置中启用任何内容才能使用此功能?

谢谢,柯克

最佳答案

我也遇到了同样的问题。以下代码对我有用:

 public async Task<IActionResult> Index()
{
if (!UserID.HasValue)
{
UpdateRemoteIp(HttpContext);
var remoteIpAddress = HttpContext.Features.Get<IHttpConnectionFeature>()?.RemoteIpAddress.ToString();
if (remoteIpAddress == null)
{
throw new Exception("Cannot determine client IP");
}
await _userService.LoginAnonymous(remoteIpAddress);
string url = UriHelper.GetDisplayUrl(Request);
return Redirect(url);
}
PrepareViewModel();
return View("Index", ViewModel);
}

private static void UpdateRemoteIp(HttpContext httpContext)
{
var xForwardedForHeaderValue = httpContext.Request.Headers.GetCommaSeparatedValues(XForwardedForHeaderName);
if (xForwardedForHeaderValue != null && xForwardedForHeaderValue.Length > 0)
{
IPAddress ipFromHeader;
int? port;
if (IPAddressWithPortParser.TryParse(xForwardedForHeaderValue[0], out ipFromHeader, out port))
{
var connection = httpContext.Connection;
var remoteIPString = connection.RemoteIpAddress?.ToString();
if (!string.IsNullOrEmpty(remoteIPString))
{
httpContext.Request.Headers[XOriginalIPName] = remoteIPString;
}
if (port.HasValue)
{
if (connection.RemotePort != 0)
{
httpContext.Request.Headers[XOriginalPortName] = connection.RemotePort.ToString(CultureInfo.InvariantCulture);
}
connection.RemotePort = port.Value;
}
connection.RemoteIpAddress = ipFromHeader;
}
}
}

希望对你有帮助

关于azure - DNX(rc1-最终版): IHttpConnectionFeature not found,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34033861/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com