从HttpRequestMessage对象获取IP地址
作者:C/S框架网  发布日期:2017-09-20 19:09:00
  从HttpRequestMessage对象获取IP地址

C# Code:

/// <summary>
/// 获取IP地址
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public static string GetIPAddress(HttpRequestMessage request)
{
   string ip = "";
   
   if (request.Properties.ContainsKey("MS_OwinContext"))
   {
      ip = ((OwinContext)request.Properties["MS_OwinContext"]).Request.RemoteIpAddress;
   }
   else if (request.Properties.ContainsKey("MS_HttpContext"))
   {
      ip = ((HttpContextWrapper)request.Properties["MS_HttpContext"]).Request.UserHostAddress;
   }
   else if (request.Properties.ContainsKey(RemoteEndpointMessageProperty.Name))
   {
      ip = ((RemoteEndpointMessageProperty)request.Properties[RemoteEndpointMessageProperty.Name]).Address;
   }
   
   if (ip == "::1") ip = "127.0.0.1";
   
   if (string.IsNullOrEmpty(ip) || !IsIP(ip))
   return "127.0.0.1";
   else
   return ip;
}

//来源:C/S框架网(www.csframework.com) QQ:1980854898


上一篇 下一篇