无法从委派Handler Web API返回HTTP Unauthorized

时间:2013-11-21 08:49:41

标签: asp.net-mvc-4 asp.net-web-api

我正在尝试在DelegatingHandler中实现身份验证。以下是一个例子。

public class AuthHandler: DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var auth = request.Headers.Authorization;
        if (!auth.Scheme.Equals("UberSecureScheme"))
        {
            return new Task<HttpResponseMessage>(() => new HttpResponseMessage(HttpStatusCode.Unauthorized)
                {
                    Content = new StringContent("You have no token")
                });
        }

        return base.SendAsync(request, cancellationToken);
    } 
}

这永远不会执行任务,也不会返回任何响应。如果我改变代码来做一些任务延续的事情,比如我已经看过一些例子,那么首先执行Controller。

return base.SendAsync(request, cancellationToken)
           .ContinueWith(task =>
           {
               var response = task.Result;
               response.StatusCode = HttpStatusCode.Unauthorized;
               return response;
           });

这显然是一场灾难。我不能让某人删除,然后告诉他们他们是未经授权的。

我也遇到过某人说只是抛出一个HTTPResponseException。无论我在那里放置什么状态代码(404,401,无论如何),浏览器总是会出现500内部服务器错误。

2 个答案:

答案 0 :(得分:7)

if (!auth.Scheme.Equals("UberSecureScheme"))
{
    var response = request.CreateResponse(HttpStatusCode.Unauthorized);
    response.ReasonPhrase = "You have no token";
    return Task.FromResult<HttpResponseMessage>(response);
}

答案 1 :(得分:0)

您可以使用Async / wait。 我键入它,而不是复制/粘贴 - 不要问,所以希望没有打字错误.... :)

protected async override Task<HttpResponseMessage>              SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
var response = await base.SendAsync(request, cancellationToken);
if (HttpContext.Current.User == null) {
    HttpResponseMessage errorResponse = new HttpResponseMessage();
    errorResponse.Headers.Add("WWW-Authenticate", "Some auth related message");
    errorResponse.StatusCode = HttpStatusCode.Unauthorized;
    return errorResponse;
}
return response;