DNX(rc1-final):未找到IHttpConnectionFeature

时间:2015-12-02 02:29:08

标签: azure dnx azure-api-apps

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

运行代码时,'context'是this.HttpContext,位于控制器方法内。

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

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

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

谢谢, 柯克

1 个答案:

答案 0 :(得分:0)

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

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

希望它可以帮到你