且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

的ASP.NET Web API:正确方法返回一个401 /未经授权的响应

更新时间:2023-02-15 17:25:08

您应该抛出一个Htt$p$psponseException$c$c>从您的API方法,而不是HttpException$c$c>:

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