【问题标题】:HTTP statuscode error for AuthorizationFilterAttributeAuthorizationFilterAttribute 的 HTTP 状态码错误
【发布时间】:2016-02-23 03:37:32
【问题描述】:

我在下面为我的 WebAPI 2 应用创建了一个自定义 AuthorizationFilterAttribute:

public class ApiKeyRequiredAttribute : AuthorizationFilterAttribute
{
    private string key;

    public ApiKeyRequiredAttribute(string key) : base()
    {
        this.key = key;
    }

    public override Task OnAuthorizationAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
    {
        IEnumerable<string> headers = new List<string>();
        actionContext.Request.Headers.TryGetValues("x-apikey", out headers);
        if (!headers.Any() || headers.Single() != this.key)
        {
            throw new SecurityException("Invalid API key provided");
        }
        return base.OnAuthorizationAsync(actionContext, cancellationToken);
    }
}

它做了它应该做的事情:具有正确标题的用户看到结果,其他人得到一个例外。但是 - 我怎样才能返回HTTP Error 401 Unauthorized?

只要我不抛出异常 - 正常的执行流程就会继续。当然我不必实现全局异常处理程序,对吧?

【问题讨论】:

    标签: asp.net-web-api2 asp.net-web-api asp.net-authorization


    【解决方案1】:

    如果不对此进行测试,您可以像这样从当前请求创建一个 ErrorResponse:-

    public class ApiKeyRequiredAttribute : AuthorizationFilterAttribute
        {
            private string key;
    
            public ApiKeyRequiredAttribute(string key)
                : base()
            {
                this.key = key;
            }
    
            public override Task OnAuthorizationAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
            {
                IEnumerable<string> headers = new List<string>();
                actionContext.Request.Headers.TryGetValues("x-apikey", out headers);
                if (!headers.Any() || headers.Single() != this.key)
                {
                    actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.Unauthorized,
                        new SecurityException("Invalid API key Provided"));
                }
                return base.OnAuthorizationAsync(actionContext, cancellationToken);
            }
        }
    

    【讨论】:

    • 谢谢 - 但这不起作用。这不会阻塞控制器方法的执行。
    • 您确定您使用的是异步变体吗?
    猜你喜欢
    • 2010-11-24
    • 1970-01-01
    • 2021-01-02
    • 2015-08-29
    • 1970-01-01
    • 1970-01-01
    • 2016-09-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多