Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return a 401 authentication error to a RestSharp client?

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);
like image 479
jaffa Avatar asked Jan 19 '12 12:01

jaffa


3 Answers

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

like image 79
jgauffin Avatar answered Nov 10 '22 14:11

jgauffin


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.

like image 4
jaffa Avatar answered Nov 10 '22 15:11

jaffa


Here are two ways to return a 401 in MVC.

return new HttpUnauthorizedResult("Unauthorized");

or

return new HttpStatusCodeResult(401);
like image 4
Daniel Pamich Avatar answered Nov 10 '22 16:11

Daniel Pamich