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" };
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…