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?

5

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.