0

我在下面为我的 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

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

4

1 回答 1

0

如果不对此进行测试,您可以像这样从当前请求创建一个 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);
        }
    }
于 2015-11-20T15:40:43.837 回答