In ASP.NET Core how do you check if request is local?

前端 未结 6 844
粉色の甜心
粉色の甜心 2020-12-15 03:15

In the regular ASP.NET you could do this in a view to determine if the current request was from localhost:

HttpContext.Current.Request.IsLocal

B

6条回答
  •  情歌与酒
    2020-12-15 03:38

    None of the above worked for me.

    Url.IsLocalUrl works very different and I find it a bit useless:

    For example, the following URLs are considered local:

      /Views/Default/Index.html
      ~/Index.html
    

    The following URLs are non-local:

      ../Index.html
      http://www.contoso.com/
      http://localhost/Index.html
    

    HttpContext.Connection.IsLocal doesn't exist in .Net Core 2.2

    Comparing ControllerContext.HttpContext.Connection.RemoteIpAddress and ControllerContext.HttpContext.Connection.LocalIpAddress also doesn't work in my test because I get "::1" for remote ip and "127.0.0.1" for local ip.

    Finally, I used this piece:

    IPAddress addr = System.Net.IPAddress.Parse( HttpContext.Connection.RemoteIpAddress.ToString() );
    if (System.Net.IPAddress.IsLoopback(addr) )
    {
        //do something
    }
    

提交回复
热议问题