Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"];
}
like image 200
Ahad Porkar Avatar asked Nov 30 '15 12:11

Ahad Porkar


1 Answers

You need to use ConnectionInfo.RemoteIpAddress instead:

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

    // ...
}
like image 123
haim770 Avatar answered Sep 30 '22 16:09

haim770