In my Mvc Api controller, if the user cannot be authenticated I throw an HttpException 401. However, the RestSharp client seems to translate this into a Http 500 status code.
I want to be able to throw HttpExceptions from my Mvc controller, and have the RestSharp client preserve the original error in its StatusCode property.
Also, I notice if the server is not up, when the RestSharp client makes a request, the reponse has a status code of 0, and a response code of Error. Should the RestSharp not return a 404 http error code instead?
What I really need is a bit of documentation on how RestSharp works with HttpCodes.
Updated with code in my api controller:
throw new HttpException((int)HttpStatusCode.Unauthorized, AuthenticationError);
Have you verified that you really return 401 to the client? ASP.NET MVC got some strange error handling sometimes.
Try to return a HttpUnauthorizedResult
instead. MSDN doc
I've been able to investigate this issue myself. Forms Authentication is set on the web app which means that when a HttpUnauthorizedResult is returned from the controller, MVC kicks in and redirects to the login page. This has the effect of the client assuming that no errors occurred.
I resolved this by using the aspnet.suppressformsredirect nuget package, and add the suppress flag into the response for authentication.
Here are two ways to return a 401 in MVC.
return new HttpUnauthorizedResult("Unauthorized");
or
return new HttpStatusCodeResult(401);
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