我需要从AuthenticationFiler返回401 Unauthorized但是当我因某种原因抛出HttpResponseException时它返回302 Found然后重定向到login.aspx。
这是我的过滤器示例:
public class MyAuthenticationFilterAttribute : Attribute, IAuthenticationFilter
{
public bool AllowMultiple { get { return false; } }
public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
{
Trace.TraceInformation("Authenticate");
throw new HttpResponseException(HttpStatusCode.Unauthorized);
}
public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
}
我只是在Startup.cs上注册它
如何从AuthenticationFiler正确返回401 Unauthorized?
答案 0 :(得分:3)
实施身份验证过滤器时,如果身份验证失败,则不应抛出HttpResponseException
。如果您发现身份验证失败,只需在传递给过滤器的ErrorResult
参数中设置HttpAuthenticationContext
属性:
public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
{
Trace.TraceInformation("Authenticate");
context.ErrorResult = new UnauthorizedResult(Enumerable.Empty<AuthenticationHeaderValue>(), context.Request);
}