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

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

HttpContext.Current.Request.IsLocal

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

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

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

 var callingUrl = Request.Headers["Referer"].ToString(); var isLocal = Url.IsLocalUrl(callingUrl); 

原始方案

我遇到了这个寻找解决方案,以了解请求是否是本地的。 不幸的是,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; } } 

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

  public IActionResult YourAction() { var isLocal = Request.IsLocal(); //... your code here } 

我希望能有所帮助。

现在它

 HttpContext.Connection.IsLocal 

如果您需要检查控制器外部,那么您将依赖IHttpContextAccessor来访问它。

根据评论更新:

HttpContext在Views中本质上可用

 @if (Context.Connection.IsLocal) { } 

在撰写本文时,.NET Core中缺少HttpContext.Connection.IsLocal

其他工作解决方案仅检查可能127.0.0.1的第一个环回地址( ::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; } } } 

和示例用例:

 app.UseWhen(HttpContextFilters.IsLocalRequest, configuration => configuration.UseElmPage()); 

我还要提一下,将以下子句添加到自定义IsLocal()检查的末尾可能很有用

 if (connection.RemoteIpAddress == null && connection.LocalIpAddress == null) { return true; } 

这将考虑使用Microsoft.AspNetCore.TestHost运行站点的情况,并且该站点在内存中完全在本地运行而没有实际的TCP / IP连接。