简体   繁体   中英

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"];
}

You need to use ConnectionInfo.RemoteIpAddress instead:

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

    // ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM