I am trying to write my own authorization attribute where I run through some custom checks on 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'm having is that I'm getting a 404 response from the web api instead of an expected 401. What am I doing wrong?
This is asp.net core 1.
Thanks in advance!
It may be because you have authentication setup to redirect to a login page for 401 responses and that login page is not being found (happened to me).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With