aspnetcore 如何在httpcontext中判断请求的action是否包含Authorize特性或Authorize特性的子类
时间: 2024-10-14 17:02:01 浏览: 24
在ASP.NET Core中,你可以通过注入`HttpContext`并在其中检查请求特征来判断某个Action是否应用了`Authorize`特性或其派生特性。以下是一个基本步骤:
1. 首先,在需要的地方注入`HttpContext`对象:
```csharp
private readonly IHttpContextAccessor _httpContextAccessor;
public YourController(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
```
2. 然后,在你需要验证权限的Action内部,获取`HttpRequest`并检查`AuthorizeAttribute`:
```csharp
[HttpGet]
public IActionResult MyAction()
{
var request = _httpContextAccessor.HttpContext.Request;
var authorizations = request.GetServices(typeof(IAuthorizationFilter)) as IAuthorizationFilter[];
if (authorizations != null && authorizations.Any(filter => filter is AuthorizeAttribute authorizeAttr && !authorizeAttr.AuthorizeAsync(request).Result))
{
// 如果Action没有Authorize特性或者授权失败,则处理未授权的情况
return Unauthorized();
}
// 如果授权成功,继续执行Action逻辑
// ...
}
```
在这里,我们首先从`HttpRequest`中获取到所有IAuthorizationFilter类型的实例,通常AuthorizeAttribute会实现这个接口。然后遍历它们,如果有任何一个是AuthorizeAttribute并且它的AuthorizeAsync方法返回false(表示未授权),就返回Unauthorized响应。
阅读全文