【发布时间】:2022-12-15 03:49:48
【问题描述】:
我正在探索 .Net 6 中的最小 API,并尝试将自定义授权过滤器应用于端点(通过属性或扩展)。
但在我看来,我做错了什么,或者它根本就不是设计成那样工作的(如果是这样的话,我很难过)。
除了最小 API 中的 [Authorize] 属性的 default usage 之外,在文档中找不到任何内容。
这是过滤器
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class CustomAuthorizeAttribute : Attribute, IAuthorizationFilter
{
//Checking tokens
}
如果我尝试在控制器级别应用它,它工作正常
[CustomAuthorize]
public class CustomController : ControllerBase
{
//Necessary routing
}
但是如果我切换到 Minimap APIs 符号并尝试使用属性
app.MapGet("/customEndpoint",
[CustomAuthorize] async ([FromServices] ICustomService customService, Guid id) =>
await customService.GetCustomStuff(id));
甚至是扩展方法
app.MapGet("/customEndpoint",
async ([FromServices] ICustomService customService, Guid id) =>
await customService.GetCustomStuff(id)).WithMetadata(new CustomAuthorizeAttribute());
它只是行不通。过滤器甚至没有被构建。
我错过了什么或做错了什么? 提前致谢
【问题讨论】:
-
当您使用控制器和属性时,MVC 框架旨在以指定的方式使用它们。这不适用于您创建的自定义类。您可能想研究是否可以通过其他方式在最小 API 中注入授权层。
-
你为什么不为此创建自定义中间件,然后将验证每个请求
-
谢谢,实际上我有这样的中间件,但我很好奇我可以在最小 API 中直接从 MVC 重用什么
-
@Beeeg ASP.NET Core MVC 包括很多不需要的管道和功能(等等不能用) 通过最少的 API - 似乎
[Authorize]就是其中之一 -不过没关系因为老实说[Authorize]属性本身非常糟糕(虽然声明性行为很好,但是有太多的移动部件和基于属性和声明性身份验证的令人沮丧的限制),所以你真的更好地使用中间件.
标签: c# asp.net .net-6.0 minimal-apis