如何使路由只能从本地主机访问?

Tad*_*dej 4 c# asp.net-core

我有一条这样的路线:

[Route("api/elasticsearch/resync/products")]
[HttpGet]
public async Task<string> ResyncProducts()
{
}
Run Code Online (Sandbox Code Playgroud)

如何使它只能从本地主机访问?

Evk*_*Evk 6

您可以使用动作过滤器并检查请求是否来自环回接口:

public class RestrictToLocalhostAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        var remoteIp = context.HttpContext.Connection.RemoteIpAddress;
        if (!IPAddress.IsLoopback(remoteIp)) {
            context.Result = new UnauthorizedResult();
            return;
        }
        base.OnActionExecuting(context);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后只需使用此属性装饰动作:

[Route("api/elasticsearch/resync/products")]
[HttpGet]
[RestrictToLocalhost]
public async Task<string> ResyncProducts()
{
}
Run Code Online (Sandbox Code Playgroud)

请注意context.HttpContext.Connection.RemoteIpAddress。如果您处于正向代理模式(某些其他Web服务器,如IIS或Nginx将请求转发给您),则该IP可能始终是localhost(因为实际上是nginx \ iis向您发出请求),甚至为null,甚至对于远程请求也是如此,如果您的应用程序配置不正确。但是,如果所有配置均正确-应该没问题。

不要像其他答案一样使用CORS。它不会阻止任何人从任何IP调用您的api。CORS是浏览器功能,在浏览器外部(恶意用户当然不会通过浏览器页面请求您的api)-它的作用完全为零。


Bra*_*ler 1

考虑使用 CORS。正确安装后,您应该能够应用如下属性 [EnableCors(origins: "http://localhost", headers: "*", methods: "*")]

请参阅此处: https ://tahirnaushad.com/2017/09/09/cors-in-asp-net-core-2-0/