Asp.net web api 如何在IAAuthenticationFilter接口中处理异常?

Asp.net web api 如何在IAAuthenticationFilter接口中处理异常?,asp.net-web-api,asp.net-web-api2,Asp.net Web Api,Asp.net Web Api2,我已使用iaauthenticationfilter接口创建了自定义身份验证类 我没有使用ChallengeAsync,而是直接抛出异常,如何处理 public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) { HttpRequestMessage request = context.Request; Authenticati

我已使用
iaauthenticationfilter接口
创建了自定义身份验证类

我没有使用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);
}
但是如何处理异常抛出?

HttpResponseException类型是一种特殊情况,因为它是专门为返回HTTP响应而设计的。
因此您不需要处理此异常。从ChallengeAsync代码中,我假设您希望在请求未经授权的情况下将身份验证头添加到响应中。您可以像这样实现它

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);
}