2

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

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

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

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

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

谢谢,柯克

4

1 回答 1

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

希望对你有帮助

于 2015-12-07T10:20:51.593 回答