Custom authorization filter always returns 404 when I try to force 401

I am trying to write my own authorization attribute, where I run some custom checks of any web api method with the CustomAuthorization attribute.

My code is as follows:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = false)] public class CustomAuthorization : AuthorizationFilterAttribute { public override void OnAuthorization(AuthorizationContext context) { //// Attempt 1 - 404 error. //// Doesnt block method with this attribute from executing (not desired behaviour). //context.HttpContext.Response.StatusCode = 401; //return; //// Attempt 2 - 404 result. //// Code with attribute doesnt execute (desired). //// Error thrown says: An exception of type 'System.Web.Http.HttpResponseException' occurred in <namespace> but was not handled in user code //// Additional information: Processing of the HTTP request resulted in an exception. Please see the HTTP response returned by the 'Response' property of this exception for details. //throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Unauthorized)); // Attempt 3 - 404 result. // Code with attribute doesnt execute (desired). context.Result = new HttpUnauthorizedResult(); } } 

The problem I am facing is that I get a 404 response from the web api instead of the expected 401. What am I doing wrong?

This is the core of asp.net 1.

Thanks in advance!

+6
source share
1 answer

Perhaps this is due to the fact that you have an authentication setting to redirect to the login page for 401 responses and that the login page was not found (it happened to me).

+7
source

All Articles