Capture request IP Address in Web API Authentication Filter
Asked Answered
V

1

13

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.

Is the request IP address available from the HttpActionContext ?

I cannot seem to find it.

Is the Authentication Filter the wrong place where to capture the IP address of the client making the request ?

Volute answered 19/5, 2015 at 20:54 Comment(0)
D
33

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();
Drisko answered 19/5, 2015 at 21:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.