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

前端 未结 7 681
再見小時候
再見小時候 2021-02-02 09:21

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

7条回答
  •  孤独总比滥情好
    2021-02-02 10:17

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

    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 Get()
    {
        var ip = _accessor.HttpContext?.Connection?.RemoteIpAddress?.ToString();
        return new string[] { ip, "value2" };
    }
    

提交回复
热议问题