سؤال

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);
هل كانت مفيدة؟

المحلول 2

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.

نصائح أخرى

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

Here are two ways to return a 401 in MVC.

return new HttpUnauthorizedResult("Unauthorized");

or

return new HttpStatusCodeResult(401);

Lame, lame, lame that we have to download a NuGet package to return a 401! My workaround is to respond with a 403 Forbidden with an explanation:

throw new HttpException((int)HttpStatusCode.Forbidden, 
  "Please log in as user " + UserId + " and try again.");

Not semantically correct, but is less work, less ongoing maintenance, and less risk.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top