ASP.NET Web API : Correct way to return a 401/unauthorised response

后端 未结 8 1214
后悔当初
后悔当初 2020-11-28 08:41

I have an MVC webapi site that uses OAuth/token authentication to authenticate requests. All the relevant controllers have the right attributes, and authentication is workin

8条回答
  •  离开以前
    2020-11-28 09:24

    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);
    

提交回复
热议问题