Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
636 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In your Startup.cs, make sure you have a method to ConfigureServices, passing in the IServiceCollection, then register IHttpContextAccessor as a singleton as follows:

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}

After registering the IHttpContextAccessor in your Startup.cs file, you can inject the IHttpContextAccessor in your controller class and use it like so:

private IHttpContextAccessor _accessor;

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...