Error trying to get client IP address in ASP.NET CORE 3.0

Asked

Viewed 30 times

1

I am searching a way to get the IP of the logged-in user

did the installation of:

Microsoft.AspNetCore.HttpOverrides 2.2.0

In Startup I added in Configure :

    app.UseForwardedHeaders(new ForwardedHeadersOptions
    {
        ForwardedHeaders = ForwardedHeaders.XForwardedFor |
        ForwardedHeaders.XForwardedProto
    });

In my controller I’m taking the IP this way:

var remoteIpAddress = Request.HttpContext.Connection.RemoteIpAddress;

I’m having an error informing that you have no support for the operation attempted

inserir a descrição da imagem aqui

1 answer

0


A more practical solution In Startup add in Configuraeservices

//Resolve a injeção de dependencia para a classe concreta em uma única instância Singleton 
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

In the Add controller :

        private readonly IHttpContextAccessor _accessor;


        public NomeController(IHttpContextAccessor accessor)
        {
            _accessor = accessor;

        }

Then and only call, when online will get the correct IP :

    var ip = _accessor.HttpContext.Connection.RemoteIpAddress.ToString();
    if (ip == "::1")
        ip = "127.0.0.1";

Browser other questions tagged

You are not signed in. Login or sign up in order to post.