3

I want to fetch client IP address using asp.net web api2 application.

I try this code but request = request ?? Request; error this line code.

the name "request" does not exist in the current context

enter image description here

public class GetIp
{
    public string IpFetch()
    {
        return GetClientIp();
    }

    private string GetClientIp(HttpRequestMessage request = null)
    {
        request = request ?? Request;
        if (request.Properties.ContainsKey("MS_HttpContext"))
        {
            return ((HttpContextWrapper)request.Properties["MS_HttpContext"]).Request.UserHostAddress;
        }
        else if (request.Properties.ContainsKey(RemoteEndpointMessageProperty.Name))
        {
            RemoteEndpointMessageProperty prop = (RemoteEndpointMessageProperty)request.Properties[RemoteEndpointMessageProperty.Name];
            return prop.Address;
        }
        else if (HttpContext.Current != null)
        {
            return HttpContext.Current.Request.UserHostAddress;
        }
        else
        {
            return null;
        }
    }
}

How to get client IP address?

Ahasanul Banna
  • 113
  • 2
  • 12
  • 3
    use this link: https://stackoverflow.com/questions/22532806/asp-net-web-api-2-1-get-client-ip-address – hassan.ef Apr 18 '19 at 05:16
  • I follow this link but error this line code >request = request ?? Request; – Ahasanul Banna Apr 18 '19 at 05:19
  • 1
    The class in the answer of the provided link inherits [`ApiController`](https://learn.microsoft.com/en-us/previous-versions/aspnet/hh834453(v%3Dvs.118)) whereas your class does not. That's why you can't access any property called `Request` (also you didn't create one yourself). – Streamline Apr 18 '19 at 05:41
  • this is a duplicate question https://stackoverflow.com/questions/9565889/get-the-ip-address-of-the-remote-host – uriz Apr 18 '19 at 05:44
  • Possible duplicate of [Asp Net Web API 2.1 get client IP address](https://stackoverflow.com/questions/22532806/asp-net-web-api-2-1-get-client-ip-address) – Marvin Klar Apr 18 '19 at 06:52

0 Answers0