Reputation: 2355
Currently I've got the following piece of code:
if (!checkAuthCode(LoginAuthenticatieCode))
{
throw new HttpException(401, "Auth Failed");
}
This code checks if the user is authenticated, and if not throws a 401 exception. The only problem being, somewhere along the way this 401 gets packaged into a nice-looking 500 error, saying
"Message": "An error has occurred.",
"ExceptionMessage": "Auth Failed",
"ExceptionType": "System.Web.HttpException",
"StackTrace": " bij WebApplication1.Controllers.loginController.checkAuthCodeOrThrow(String LoginAuthenticatieCode) in blablabla
Is there a way to prevent ASP.NET (or MVC, I don't know which of the two is responsible) from wrapping my error in this "nice" human-readable form?
Upvotes: 0
Views: 1309
Reputation: 151586
It looks like this is a WebAPI controller, and you're throwing an MVC exception. This difference will be unified with MVC 6 / vNext.
For now, MVC and WebAPI use different assemblies and namespaces. The System.Web.HttpException
you throw is not recognized as an HTTP exception by WebAPI, so it thinks your application has thrown a random exception and formats that as a JSON-formatted 500 Internal Server Error.
So for WebAPI, throw a new HttpResponseException(HttpStatusCode.Unauthorized)
. This will generate an HTTP 401.
Upvotes: 3
Reputation: 1895
For ASP.NET MVC use HttpException(401, "Some message...")
.
For ASP.NET WebAPI use HttpResponseException(HttpStatusCode.Unauthorized)
.
Upvotes: 2