How to get Client IP address in ASP.NET Core 2.1

2020-05-25 02:34发布

I'm working on ASP.Net Core 2.1 with Angular Template provided by Microsoft Visual Studio 2017. My Client App is working fine. After competition of User Authentication, I want to start User Session Management in which I store client user IP Address. I've already searched for this on the internet but so far not found any solution.

Below are some ref links which I already visited:

How do I get client IP address in ASP.NET CORE?

Get Client IP Address in ASP.NET Core 2.0

Get a user remote IP Address in ASP.Net Core

In my ValuesController.cs I also tried below code:

private IHttpContextAccessor _accessor;

public ValuesController(IHttpContextAccessor accessor)
{
    _accessor = accessor;
}

public IEnumerable<string> Get()
{
    var ip = Request.HttpContext.Connection.RemoteIpAddress.ToString();
    return new string[] { ip, "value2" };
}

wherein ip variable I get null value and getting this error

Request.HttpContext.Connection.RemoteIpAddress.Address threw an exception of Type 'System.Net.Sockets.SocketException'

enter image description here

enter image description here

Can you please let me know how to get client IP address in ASP.NET Core 2.1.

7条回答
放我归山
2楼-- · 2020-05-25 03:06

If your Kestrel sits behind a reverse proxy like IIS make sure to forward the headers containing the client IP.
This goes into startup:

app.UseForwardedHeaders(new ForwardedHeadersOptions{ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto});
查看更多
登录 后发表回答