// 使用 filter
[Route("api/[controller]")]
[ApiController]
[Authorize]
[TypeFilter(typeof(CustomAsyncAuthorizationFilter))]
public class Controller1 : ControllerBase
// 定義 filter
public sealed class CustomAsyncAuthorizationFilter : IAsyncAuthorizationFilter
{
public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
{
bool isAuthorized = await CheckUserAuthorizationAsync(context);
if (!isAuthorized) context.Result = new ForbidResult();
}
private async Task<bool> CheckUserAuthorizationAsync(AuthorizationFilterContext context)
{
// do something and return bool
}
}