在ASP.NET Core中,如何检查请求是否为本地? [英] In ASP.NET Core how do you check if request is local?
问题描述
在常规ASP.NET中,您可以通过执行此操作来确定当前请求是否来自本地主机:
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
但是无论如何,在ASP.NET 6/Core/中我都找不到类似的东西.
But I can't find something similar in ASP.NET 6/Core/whatever it is meant to be called.
推荐答案
更新:ASP.NET Core 2.0具有一种称为Url.IsLocalUrl
的方法(请参见此我认为该代码可以工作,但是我无法对其进行完整的测试
I think this code will work, but I haven't been able to test it completely
var callingUrl = Request.Headers["Referer"].ToString();
var isLocal = Url.IsLocalUrl(callingUrl);
但是请参见下面Will Dean对这种方法的评论:
But see Will Dean's comment below about this approach:
任何想使用更新"版本来检查Referrer标头的人都应牢记,标头极易被欺骗,在某种程度上不适用于环回IP地址.
Anyone thinking about using the 'updated' version which checks the Referrer header should bear in mind that headers are extremely easy to spoof, to a degree that doesn't apply to loopback IP addresses.
原始解决方案
我碰到了这种情况,它在寻找一种解决方案来知道请求是否是本地的.不幸的是,ASP.NET 1.1.0版在连接上没有IsLocal
方法.我在名为 Strathweb ,但那也已经过时了.
I came across this looking for a solution to knowing if a request is local. Unfortunately ASP.NET version 1.1.0 does not have a IsLocal
method on a connection. I found one solution on a web site called Strathweb but that is out of date too.
我已经创建了自己的IsLocal
扩展名,并且似乎可以使用,但是我不能说我已经在所有情况下都进行了测试,但是欢迎您尝试一下.
I have created my own IsLocal
extension, and it seems to work, but I can't say I have tested it in all circumstances, but you are welcome to try it.
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
属性(即
You call it in a controller action from using the Request
property, i.e.
public IActionResult YourAction()
{
var isLocal = Request.IsLocal();
//... your code here
}
我希望能对某人有所帮助.
I hope that helps someone.
这篇关于在ASP.NET Core中,如何检查请求是否为本地?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!