如何在IAuthenticationFilter接口中处理异常?

时间:2017-07-20 06:13:57

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

created custom Authentication class使用IAuthenticationFilter interface

而不是使用ChallengeAsync我直接抛出异常如何处理它?

public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
{
    HttpRequestMessage request = context.Request;
    AuthenticationHeaderValue authorization = request.Headers.Authorization;
    if (authorization == null)
    {
           throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest,"FAIL"));
    }


public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
{
        //var challenge = new AuthenticationHeaderValue("Basic");
        //context.Result = new AddChallengeOnUnauthorizedResult(challenge, context.Result);
        //return Task.FromResult(0);
}

但如何处理异常抛出?

1 个答案:

答案 0 :(得分:1)

From documentation: HttpResponseException类型是一种特殊情况,因为它专门用于返回HTTP响应。
因此,您不需要处理此异常。从ChallengeAsync代码,我想如果请求未经授权,您希望在响应中添加身份验证标头。你可以实现它

public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
{
    HttpRequestMessage request = context.Request;
    var challenge = new AuthenticationHeaderValue("Basic");
    var response = request.CreateResponse(HttpStatusCode.BadRequest, "FAIL");
    response.Headers.WwwAuthenticate.Add(challenge);
    throw new HttpResponseException(response);
}