1

I have a function that catches errors And when an error occurs I check if it is an AJAX error And if this AJAX changes the status of the error to 401 Unauthorized I changed both the Result and the status Code like this:

     filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
     filterContext.Result = new HttpStatusCodeResult(System.Net.HttpStatusCode.Unauthorized);
     filterContext.HttpContext.Response.SuppressFormsAuthenticationRedirect = true;

When I debug in c# I really see them 401 as what I changed and then it goes back to JS and there is 500 inside does anyone know why?

Thank you

Lior Lev
  • 143
  • 7
  • https://stackoverflow.com/questions/10655350/returning-http-status-code-from-web-api-controller This may help you – samiksc Dec 15 '20 at 06:23
  • My function is void and it does not return HttpResponseMessage I need to fill FilterContext with data – Lior Lev Dec 15 '20 at 06:45

2 Answers2

1

Ok I was able to solve the problem

I should have simply added this sentence:

filterContext.ExceptionHandled = true;

Thanks

And good luck to everyone

Lior Lev
  • 143
  • 7
0

You should be throwing a HttpResponseException from your API method, not HttpException:

throw new HttpResponseException(HttpStatusCode.Unauthorized);
  • I did what you said and he throws me an error :"System.Web.Http.HttpResponseException: 'Processing of the HTTP request resulted in an exception. Please see the HTTP response returned by the 'Response' property of this exception for details.'" – Lior Lev Dec 15 '20 at 06:49