如何在ASP.NET Core 2.1中获取客户端IP地址

如何在ASP.NET Core 2.1中获取客户端IP地址

问题描述:

我正在使用Microsoft Visual Studio 2017提供的带有Angular模板的ASP.Net Core 2.1.我的客户端应用程序运行正常.经过用户身份验证的竞争之后,我想启动用户会话管理,在其中存储客户端用户IP地址.我已经在互联网上搜索了此文件,但到目前为止没有找到任何解决方案.

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:

如何获取客户端IP地址在ASP.NET CORE中?

在ASP.NET Core 2.0中获取客户端IP地址

获取用户远程IP地址在ASP.Net Core中

在ValuesController.cs中,我还尝试了以下代码:

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" };
}

其中ip变量获得空值并出现此错误

wherein ip variable I get null value and getting this error

Request.HttpContext.Connection.RemoteIpAddress.Address引发了类型为'System.Net.Sockets.SocketException'的异常

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

能否让我知道如何在ASP.NET Core 2.1中获取客户端IP地址.

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

在您的Startup.cs中,确保您有一个ConfigureConfigs方法,传入IServiceCollection,然后将IHttpContextAccessor注册为单例,如下所示:

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>();
}

Startup.cs文件中注册IHttpContextAccessor后,可以将IHttpContextAccessor注入到控制器类中,并按如下方式使用它:

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" };
}