.NETAsp.net开发WebApi

DotNet获取客户端的IP地址

2018-07-31  本文已影响34人  CoderMiner

DotNet获取客户端的IP地址

image
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;
        }
    }
    if (request.Properties.ContainsKey(OwinContext))
    {
        dynamic ctx = request.Properties[OwinContext];
        if (ctx != null)
        {
            return ctx.Request.RemoteIpAddress;
        }
    }
    return null;
}

原文连接

上一篇下一篇

猜你喜欢

热点阅读