基于策略的授权中引发异常

时间:2019-03-19 08:23:33

标签: c# asp.net-core asp.net-core-mvc asp.net-core-webapi

我已经在我的WebApi项目中实现了基于策略的授权。它工作正常,唯一的问题是我无法更改失败消息。经过一番调查,我发现此功能尚未实现。 Issue tracked here。作为一种解决方法,我正在考虑引发一个异常而不是context.Fail()

这是个好主意吗?可以有一些问题吗?

示例代码:

public class MySampleAuthorizationHandler : AuthorizationHandler<MySampleRequirement>
{
    protected override async Task HandleRequirementAsync(
        AuthorizationHandlerContext context,
        MySampleRequirement requirement)
    {
        if (true)
        {
            throw new UnauthorizedAccessException("My custom message");
        }
        else
        {
            context.Succeed(requirement);
        }
        return Task.CompletedTask;
    }
}

0 个答案:

没有答案
相关问题