ASP.NET Web API : Correct way to return a 401/unauthorised response
You should be throwing a HttpResponseException
from your API method, not HttpException
:
throw new HttpResponseException(HttpStatusCode.Unauthorized);
Or, if you want to supply a custom message:
var msg = new HttpResponseMessage(HttpStatusCode.Unauthorized) { ReasonPhrase = "Oops!!!" };
throw new HttpResponseException(msg);
Just return the following:
return Unauthorized();