WebAPI 2 IAuthenticationFilter返回401

时间:2017-12-02 05:37:49

标签: c# asp.net .net asp.net-web-api2

我需要从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?

1 个答案:

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