【问题标题】:In ASP.NET Core 6, is there a way to restrict certain action methods based on which URL is used?在 ASP.NET Core 6 中,有没有办法根据使用的 URL 来限制某些操作方法?
【发布时间】:2022-01-29 03:01:08
【问题描述】:

在面向 .NET 6 的默认 ASP.NET Core Web API 应用程序中,默认情况下它公开两个 URL 端点:一个位于 http://localhost:50xx,另一个位于 https://localhost:70xx。

我想要做的是将第一个 (http) 用于内部/受信任的客户端请求,将第二个 (https) 用于 Internet/公共请求。所以很自然地,我想根据请求的不同来处理请求。

对于这两种类型的请求,我想使用简单/默认路由匹配,然而,对于 HTTPS 请求,我想对选定的操作方法制定白名单。结果是大多数请求根本无法通过 HTTPS 获得。

我觉得必须有一些简单的方法来做到这一点,因为框架(和默认的应用程序模板)似乎已经通过提供两个 URL 来让球朝着这个方向发展......必须有一些方便的方法这正是我所描述的,但我没有在文档中遇到它们。

谢谢

【问题讨论】:

标签: asp.net-core asp.net-core-webapi .net-6.0


【解决方案1】:

实施并应用全局自定义 ActionFilterAttribute,它禁止 HTTPS 请求,但应用了自定义属性的控制器/操作除外。

1. 创建一个自定义属性,该属性将应用于支持 HTTPS 请求的控制器/方法:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class AllowHttpsAttribute : Attribute { }

2. 创建一个自定义 ActionFilterAttribute,当控制器或操作未应用 AllowHttpsAttribute 时,它会短路通过 HTTPS 发出的请求(短路是通过给context.Result赋值来完成的:

public class HttpOnlyActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        var isHttps = context.HttpContext.Request.Scheme == Uri.UriSchemeHttps;
        if (isHttps && HttpsNotSupported(context))
        {
            context.Result = new BadRequestResult();
        }
    }

    private bool HttpsNotSupported(ActionContext context)
    {
        return context.ActionDescriptor is ControllerActionDescriptor x &&
        !x.ControllerTypeInfo.GetCustomAttributes<AllowHttpsAttribute>().Any() &&
        !x.MethodInfo.GetCustomAttributes<AllowHttpsAttribute>().Any();
    }
}

3. 全局应用HttpOnlyActionFilter(在Program.cs中):

builder.Services.AddControllers(x => x.Filters.Add<HttpOnlyActionFilter>());

用法:

应用于行动:

public class Controller : ControllerBase
{
    // Allow requests over HTTPS 
    [HttpGet, AllowHttps]
    public ActionResult Action1() => ...;

    // Disallow requests over HTTPS 
    [HttpGet]
    public ActionResult Action2() => ...;
}

应用于控制器:

[AllowHttps] // Allow requests over HTTPS 
public class Controller : ControllerBase
{
  ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-07
    • 2010-11-06
    相关资源
    最近更新 更多