在常规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)
我希望能有所帮助.
在编写本文时HttpContext.Connection.IsLocal
,.NET Core现在缺少了.
其他工作解决方案仅检查可能不合适的第一个环回地址(::1
或127.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)
归档时间: |
|
查看次数: |
12679 次 |
最近记录: |