我正在使用Microsoft Visual Studio 2017提供的Angular模板开发ASP.Net Core 2.1.我的客户端应用程序工作正常.在用户身份验证的竞争之后,我想启动用户会话管理,其中我存储客户端用户IP地址.我已经在互联网上搜索过这个,但到目前为止还没有找到任何解决方案.
以下是我访问过的一些参考链接:
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
在我的ValuesController.cs中,我也试过下面的代码:
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变量我得到空值并得到此错误
Request.HttpContext.Connection.RemoteIpAddress.Address threw an exception of Type ‘System.Net.Sockets.SocketException’
你能告诉我如何在ASP.NET Core 2.1中获取客户端IP地址吗?
解决方法
在您的Startup.cs中,确保您有一个ConfigureServices方法,传入IServiceCollection,然后将IHttpContextAccessor注册为单例,如下所示:
public void ConfigureServices(IServiceCollection services) { services.AddSingleton<IHttpContextAccessor,HttpContextAccessor>(); }
在Startup.cs文件中注册IHttpContextAccessor后,可以在控制器类中注入IHttpContextAccessor并使用它,如下所示:
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" }; }