Search code examples
.net.net-coreasp.net-core-webapiasp.net-apicontroller

How to get API caller detail info in .NET Core 2.1?


How to get possible detail caller info whoever consuming my API in .NET Core 2.1?

Here is how I designed API endpoint:

enter image description here


Solution

  • According to your description, I suggest you could use httpcontextaccessor's httprequest context to get the client information.

    If you want to use this in your controller, you should firstly register the startup.cs.

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddHttpContextAccessor();
    
            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "CoreAPINormalIssue", Version = "v1" });
            });
        }
    

    Then inside the controller, you should use below codes:

        private readonly IHttpContextAccessor _httpContextAccessor;
    
        public WeatherForecastController(ILogger<WeatherForecastController> logger, IHttpContextAccessor httpContextAccessor)
        {
            _logger = logger;
            _httpContextAccessor = httpContextAccessor;
        }
    

    Then inside the controller:

    // Get the client IP address.
    var re =  _httpContextAccessor.HttpContext.Connection.RemoteIpAddress;
    

    More details, you could refer to this article.