【问题标题】:DNX (rc1-final): IHttpConnectionFeature not foundDNX(rc1-final):未找到 IHttpConnectionFeature
【发布时间】:2015-12-02 02:29:08
【问题描述】:

使用最新的 rc1-final 版本的 ASP.NET 5,我试图在 Azure API App 控制器方法中找到远程 IP 地址。

运行代码时,'context' 是 this.HttpContext,在控制器方法中。

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

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

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

谢谢, 柯克

【问题讨论】:

  • 你能发布你的startup.cs吗?我的情况是它正在工作,所以我可以检查它。

标签: azure dnx azure-api-apps


【解决方案1】:

我遇到了同样的问题。 以下代码适用于我:

 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;
            }
        }
    }

希望对你有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多