在常规ASP.NET,你可以在视图中这样做是为了确定当前的请求是从本地主机:在ASP.NET核心如何检查请求是否是本地的?
HttpContext.Current.Request.IsLocal
但我无法找到ASP.NET类似的东西6 /核心/不管它是什么意思。
在此先感谢
在常规ASP.NET,你可以在视图中这样做是为了确定当前的请求是从本地主机:在ASP.NET核心如何检查请求是否是本地的?
HttpContext.Current.Request.IsLocal
但我无法找到ASP.NET类似的东西6 /核心/不管它是什么意思。
在此先感谢
本质可我碰到这个寻找一个解决方案,以知道,如果一个请求是本地的来了。不幸的是,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
}
我希望可以帮助别人。
这对我有帮助。 [这里](https://gist.github.com/firelizzard18/74e7481fb97c16b90bfd801798f53319)是我的版本。 –
现在它
HttpContext.Connection.IsLocal
,如果你需要检查控制器的那个之外,那么你采取IHttpContextAccessor依赖于访问它。
更新基于评论:
HttpContext的是在浏览
@if (Context.Connection.IsLocal)
{
}
我通过执行@inject IHttpContextAccessor Context来获取视图中的依赖关系;对吧?目前本地永远是假的... –
这是在RC2中消失。菲利普在这里有一个替代方法:http://www.strathweb.com/2016/04/request-islocal-in-asp-net-core/但即使它似乎严重依赖于其他中间件和你使用的服务器。 – ssmith
在撰写本文时,dotnet core现在缺少HttpContext.Connection.IsLocal。
其他工作解决方案仅检查第一个环回地址(:: 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;
}
}
}
和示例使用案例:
app.UseWhen(HttpContextFilters.IsLocalRequest, configuration => configuration.UseElmPage());
我还要提到,它可能是有用的,下面的子句添加到年底你定制IsLocal()
检查
if (connection.RemoteIpAddress == null && connection.LocalIpAddress == null)
{
return true;
}
这将考虑到站点正在使用Microsoft.AspNetCore.TestHost
运行,并且该站点在内存中完全在本地运行,而没有实际的TCP/IP连接。
请小心使用'HttpContext.Connection.IsLocal'。在我看来,'HttpContext.Connection.RemoteIpAddress'的使用是**更安全的方式**。如果我连接到本地测试ASP.NET 5 RC1项目,我会在'RemoteIpAddress'中看到':: 1',但'HttpContext.Connection.IsLocal'是'false'。这是不对的。 – Oleg
干杯奥列格,你说的话对我来说也是如此。 –
我也得到同样的行为。本地总是“假”。 –