2017-12-02 3 views
0

Ich muss 401 Unauthorized vom AuthenticationFiler zurückgeben, aber wenn ich HttpResponseException aus irgendeinem Grund werfe, gibt es 302 Found zurück und leitet dann zu login.aspx um.WebAPI 2 IAuthenticationFilter gibt 401 zurück

Hier ist mein Filter Beispiel:

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

und ich es nur auf Startup.cs registrieren

Wie kann ich Unauthorized von AuthenticationFiler zurückkehren 401 richtig?

Antwort

3

Wenn Sie den Authentifizierungsfilter implementieren, sollten Sie HttpResponseException nicht senden, wenn die Authentifizierung fehlgeschlagen ist. Wenn Sie, dass die Authentifizierung nicht erkennen, setzen nur ErrorResult Eigenschaft in HttpAuthenticationContext Parameter auf den Filter geleitet:

public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) 
{ 
    Trace.TraceInformation("Authenticate"); 

    context.ErrorResult = new UnauthorizedResult(Enumerable.Empty<AuthenticationHeaderValue>(), context.Request); 
} 
+0

Um zu dieser Antwort hinzufügen, sind Ausnahmen teuer. Du willst sie auf ein Minimum beschränken :) – gldraphael

Verwandte Themen