[c#] Asp Net Web API 2.1 get client IP address

Hello I need get client IP that request some method in web api, I have tried to use this code from here but it always returns server local IP, how to get in correct way ?

HttpContext.Current.Request.UserHostAddress;

from other questions:

public static class HttpRequestMessageExtensions
    {
        private const string HttpContext = "MS_HttpContext";
        private const string RemoteEndpointMessage = "System.ServiceModel.Channels.RemoteEndpointMessageProperty";

        public static string GetClientIpAddress(this HttpRequestMessage request)
        {
            if (request.Properties.ContainsKey(HttpContext))
            {
                dynamic ctx = request.Properties[HttpContext];
                if (ctx != null)
                {
                    return ctx.Request.UserHostAddress;
                }
            }

            if (request.Properties.ContainsKey(RemoteEndpointMessage))
            {
                dynamic remoteEndpoint = request.Properties[RemoteEndpointMessage];
                if (remoteEndpoint != null)
                {
                    return remoteEndpoint.Address;
                }
            }

            return null;
        }
    }

This question is related to c# asp.net asp.net-web-api

The answer is


With Web API 2.2: Request.GetOwinContext().Request.RemoteIpAddress


It's better to cast it to HttpContextBase, this way you can mock and test it more easily

public string GetUserIp(HttpRequestMessage request)
{
    if (request.Properties.ContainsKey("MS_HttpContext"))
    {
        var ctx = request.Properties["MS_HttpContext"] as HttpContextBase;
        if (ctx != null)
        {
            return ctx.Request.UserHostAddress;
        }
    }

    return null;
}

Replying to this 4 year old post, because this seems overcomplicated to me, at least if you're hosting on IIS.

Here's how I solved it:

using System;
using System.Net;
using System.Web;
using System.Web.Http;
...
[HttpPost]
[Route("ContactForm")]
public IHttpActionResult PostContactForm([FromBody] ContactForm contactForm)
    {
        var hostname = HttpContext.Current.Request.UserHostAddress;
        IPAddress ipAddress = IPAddress.Parse(hostname);
        IPHostEntry ipHostEntry = Dns.GetHostEntry(ipAddress);
        ...

Unlike OP, this gives me the client IP and client hostname, not the server. Perhaps they've fixed the bug since then?


string userRequest = System.Web.HttpContext.Current.Request.UserHostAddress;

This works on me.

System.Web.HttpContext.Current.Request.UserHostName; this one return me the same return I get from the UserHostAddress.


My solution is similar to user1587439's answer, but works directly on the controller's instance (instead of accessing HttpContext.Current).

In the 'Watch' window, I saw that this.RequestContext.WebRequest contains the 'UserHostAddress' property, but since it relies on the WebHostHttpRequestContext type (which is internal to the 'System.Web.Http' assembly) - I wasn't able to access it directly, so I used reflection to directly access it:

string hostAddress = ((System.Web.HttpRequestWrapper)this.RequestContext.GetType().Assembly.GetType("System.Web.Http.WebHost.WebHostHttpRequestContext").GetProperty("WebRequest").GetMethod.Invoke(this.RequestContext, null)).UserHostAddress;

I'm not saying it's the best solution. using reflection may cause issues in the future in case of framework upgrade (due to name changes), but for my needs it's perfect


I think this is the most clear solution, using an extension method:

public static class HttpRequestMessageExtensions
{
    private const string HttpContext = "MS_HttpContext";
    private const string RemoteEndpointMessage = "System.ServiceModel.Channels.RemoteEndpointMessageProperty";

    public static string GetClientIpAddress(this HttpRequestMessage request)
    {
        if (request.Properties.ContainsKey(HttpContext))
        {
            dynamic ctx = request.Properties[HttpContext];
            if (ctx != null)
            {
                return ctx.Request.UserHostAddress;
            }
        }

        if (request.Properties.ContainsKey(RemoteEndpointMessage))
        {
            dynamic remoteEndpoint = request.Properties[RemoteEndpointMessage];
            if (remoteEndpoint != null)
            {
                return remoteEndpoint.Address;
            }
        }

        return null;
    }
}

So just use it like:

var ipAddress = request.GetClientIpAddress();

We use this in our projects.

Source/Reference: Retrieving the client’s IP address in ASP.NET Web API


If you're self-hosting with Asp.Net 2.1 using the OWIN Self-host NuGet package you can use the following code:

 private string getClientIp(HttpRequestMessage request = null)
    {
        if (request == null)
        {
            return null;
        }

        if (request.Properties.ContainsKey("MS_OwinContext"))
        {
            return ((OwinContext) request.Properties["MS_OwinContext"]).Request.RemoteIpAddress;
        }
        return null;
    }

Try to get the Ip using

ip = HttpContext.Current != null ? HttpContext.Current.Request.UserHostAddress : "";

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to asp.net-web-api

Entity Framework Core: A second operation started on this context before a previous operation completed FromBody string parameter is giving null How to read request body in an asp.net core webapi controller? JWT authentication for ASP.NET Web API Token based authentication in Web API without any user interface Web API optional parameters How do I get the raw request body from the Request.Content object using .net 4 api endpoint How to use a client certificate to authenticate and authorize in a Web API HTTP 415 unsupported media type error when calling Web API 2 endpoint The CodeDom provider type "Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider" could not be located