Capture request IP Address in Web API Authentication Filter

后端 未结 1 570
野性不改
野性不改 2021-02-19 22:36

I would like to capture the IP Address of the client that calls my Web API service. I am trying to capture that IP address in a custom Authentication Filter that I have created.

相关标签:
1条回答
  • 2021-02-19 23:13

    I recently found the following extension method for that:

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

    You can now call:

    HttpActionContext.Request.GetClientIpAddress();
    
    0 讨论(0)
提交回复
热议问题