获取连接到C#.NET WebAPI应用程序

时间:2016-06-29 09:44:53

标签: c# .net asp.net-web-api ip asp.net-web-api2

我试过了:

private const string HttpContext = "MS_HttpContext";
private const string RemoteEndpointMessage = "System.ServiceModel.Channels.RemoteEndpointMessageProperty";

public static string GetClientIpAddress(HttpRequestMessage request)
{
    if (request.Properties.ContainsKey(HttpContext))
    {
        dynamic ctx = request.Properties[HttpContext];
        if (ctx != null)
        {
            return ctx.Request.UserHostAddress;
        }
    }

    if (request.Properties.ContainsKey(RemoteEndpointMessage))
    {
        dynamic remoteEndpoint = request.Properties[RemoteEndpointMessage];
        if (remoteEndpoint != null)
        {
            return remoteEndpoint.Address;
        }
    }

    return null;
}

根据:

Retrieving the client's IP address in ASP.Net Web API

这是应该对自托管主机和webapi主机有效的组合方法。不幸的是,我得到null而不是IP地址。

我在本地尝试,因此我希望127.0.0.1localhost作为IP地址

1 个答案:

答案 0 :(得分:11)

以下是您所拥有的扩展版本。

static class HttpRequestMessageExtensions {

    private const string HttpContext = "MS_HttpContext";
    private const string RemoteEndpointMessage = "System.ServiceModel.Channels.RemoteEndpointMessageProperty";
    private const string OwinContext = "MS_OwinContext";

    public static string GetClientIpString(this HttpRequestMessage request) {
        //Web-hosting
        if (request.Properties.ContainsKey(HttpContext)) {
            dynamic ctx = request.Properties[HttpContext];
            if (ctx != null) {
                return ctx.Request.UserHostAddress;
            }
        }
        //Self-hosting
        if (request.Properties.ContainsKey(RemoteEndpointMessage)) {
            dynamic remoteEndpoint = request.Properties[RemoteEndpointMessage];
            if (remoteEndpoint != null) {
                return remoteEndpoint.Address;
            }
        }
        //Owin-hosting
        if (request.Properties.ContainsKey(OwinContext)) {
            dynamic ctx = request.Properties[OwinContext];
            if (ctx != null) {
                return ctx.Request.RemoteIpAddress;
            }
        }
        if (System.Web.HttpContext.Current != null) {
            return System.Web.HttpContext.Current.Request.UserHostAddress;
        }
        // Always return all zeroes for any failure
        return "0.0.0.0";
    }

    public static IPAddress GetClientIpAddress(this HttpRequestMessage request) {
        var ipString = request.GetClientIpString();
        IPAddress ipAddress = new IPAddress(0);
        if (IPAddress.TryParse(ipString, out ipAddress)) {
            return ipAddress;
        }

        return ipAddress;
    }

}

假设您在控制器中,上述扩展方法允许进行如下调用:

HttpRequestMessage request = this.Request;

var ip = request.GetClientIpString();