Ahad Porkar
Ahad Porkar

Reputation: 1698

Accessing Client IP Address (REMOTE_ADDR) in Asp.Net 5

Im trying to get ServerVariables["REMOTE_ADDR"] in asp.net.

this is my old code (webapi 2) :

private Logn GLog(System.Web.Routing.RequestContext requestContext)
{
    Ln Log = new LogInformation();
    Lg.IP = requestContext.HttpContext.Request.ServerVariables["REMOTE_ADDR"];
    Lg.RemoteIP = requestContext.HttpContext.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
    ............................

from What I've Learned they changed "Routing.RequestContext" to

"IHttpContextAccessor" in vNext version.

how can i achive above result with IHttpContextAccessor ?

this gave me error on "ServerVariables" part:

private Logn GLog(IHttpContextAccessor requestContext)
{
    Ln Log = new LogInformation();
    Lg.IP = requestContext.HttpContext.Request.ServerVariables["REMOTE_ADDR"];
}

Upvotes: 6

Views: 4256

Answers (1)

haim770
haim770

Reputation: 49095

You need to use ConnectionInfo.RemoteIpAddress instead:

private Logn GLog(IHttpContextAccessor contextAccessor)
{
    Ln Log = new LogInformation();
    Lg.IP = contextAccessor.HttpContext.Connection.RemoteIpAddress.ToString();

    // ...
}

Upvotes: 11

Related Questions