我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);
}
但如何处理异常抛出?
答案 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);
}