在常规的ASP.NET中,可以在视图中执行此操作以确定当前请求是否来自本地主机:
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);
但是请参阅下面的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;
}
}
您可以使用Request
属性在控制器动作中调用它,即
public IActionResult YourAction()
{
var isLocal = Request.IsLocal();
//... your code here
}
希望对您有所帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句