Asp.net-Web-Api

在 Web API 身份驗證過濾器中擷取請求 IP 地址

  • June 25, 2018

我想擷取呼叫我的 Web API 服務的客戶端的 IP 地址。我正在嘗試在我創建的自定義身份驗證過濾器中擷取該 IP 地址。

請求 IP 地址是否可從HttpActionContext?

我似乎找不到它。

身份驗證過濾器是否在錯誤的位置擷取發出請求的客戶端的 IP 地址?

我最近為此找到了以下擴展方法:

public static string GetClientIpAddress(this HttpRequestMessage request)
{
   if (request.Properties.ContainsKey("MS_HttpContext"))
   {
       return IPAddress.Parse(((HttpContextBase)request.Properties["MS_HttpContext"]).Request.UserHostAddress).ToString();
   }
   if (request.Properties.ContainsKey("MS_OwinContext"))
   {
       return IPAddress.Parse(((OwinContext)request.Properties["MS_OwinContext"]).Request.RemoteIpAddress).ToString();
   }
   return null;
}

您現在可以呼叫:

HttpActionContext.Request.GetClientIpAddress();

引用自:https://stackoverflow.com/questions/30335955