在ASP.NET Core中,如何检查请求是否是本地的?

Mar*_*nce 28 c# asp.net-core

在常规ASP.NET中,您可以在视图中执行此操作以确定当前请求是否来自localhost:

HttpContext.Current.Request.IsLocal

但我无法在ASP.NET 6/Core /中找到类似的内容.

Jon*_*ith 20

更新:ASP.NET Core 2.0有一个名为Url.IsLocalUrl(请参阅此Microsoft Docs)的方法.

认为这段代码可行,但我无法完全测试它

var callingUrl = Request.Headers["Referer"].ToString();
var isLocal = Url.IsLocalUrl(callingUrl);
Run Code Online (Sandbox Code Playgroud)

但请参阅Will Dean关于此方法的评论:

任何考虑使用检查Referrer标头的"更新"版本的人都应该记住,标头非常容易欺骗,其程度不适用于环回IP地址.


原始解决方案

我遇到了这个寻找解决方案,以了解请求是否是本地的.不幸的是,ASP.NET 1.1.0版IsLocal在连接上没有方法.我在名为Strathweb的网站上找到了一个解决方案,但这也是过时的.

我创建了自己的IsLocal扩展,它似乎工作,但我不能说我已经在所有情况下测试过它,但欢迎你尝试一下.

public static class IsLocalExtension
{
    private const string NullIpAddress = "::1";

    public static bool IsLocal(this HttpRequest req)
    {
        var connection = req.HttpContext.Connection;
        if (connection.RemoteIpAddress.IsSet())
        {
            //We have a remote address set up
            return connection.LocalIpAddress.IsSet() 
                  //Is local is same as remote, then we are local
                ? connection.RemoteIpAddress.Equals(connection.LocalIpAddress) 
                  //else we are remote if the remote IP address is not a loopback address
                : IPAddress.IsLoopback(connection.RemoteIpAddress);
        }

        return true;
    }

    private static bool IsSet(this IPAddress address)
    {
        return address != null && address.ToString() != NullIpAddress;
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以使用Request属性在控制器操作中调用它,即

 public IActionResult YourAction()
 {
     var isLocal = Request.IsLocal();
     //... your code here
 }
Run Code Online (Sandbox Code Playgroud)

我希望能有所帮助.

  • 任何考虑使用检查 Referrer 标头的“更新”版本的人都应该记住,标头极容易被欺骗,在某种程度上不适用于环回 IP 地址。 (4认同)
  • 这对我有帮助.[这里](https://gist.github.com/firelizzard18/74e7481fb97c16b90bfd801798f53319)是我的版本. (3认同)

too*_*too 8

在编写本文时HttpContext.Connection.IsLocal,.NET Core现在缺少了.

其他工作解决方案仅检查可能不合适的第一个环回地址(::1127.0.0.1).

我发现下面的解决方案很有用:

using Microsoft.AspNetCore.Http;
using System.Net;

namespace ApiHelpers.Filters
{
    public static class HttpContextFilters
    {
        public static bool IsLocalRequest(HttpContext context)
        {
            if (context.Connection.RemoteIpAddress.Equals(context.Connection.LocalIpAddress))
            {
                return true;
            }
            if (IPAddress.IsLoopback(context.Connection.RemoteIpAddress))
            {
                return true;
            }
            return false;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

和示例用例:

app.UseWhen(HttpContextFilters.IsLocalRequest, configuration => configuration.UseElmPage());
Run Code Online (Sandbox Code Playgroud)

  • 这个方法可以简化为`public static bool IsLocalRequest(HttpContext context)=> context.Connection.RemoteIpAddress.Equals(context.Connection.LocalIpAddress)|| IPAddress.IsLoopback(context.Connection.RemoteIpAddress);`. (4认同)