ASP.NET Web API:返回 401/未授权响应的正确方法 [英] ASP.NET Web API : Correct way to return a 401/unauthorised response
问题描述
我有一个 MVC webapi 站点,它使用 OAuth/令牌身份验证来验证请求.所有相关控制器都具有正确的属性,并且身份验证工作正常.
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 working ok.
问题是并不是所有的请求都可以在一个属性的范围内被授权——必须在控制器方法调用的代码中执行一些授权检查——返回 401 未授权响应的正确方法是什么?这种情况?
The problem is that not all of the request can be authorised in the scope of an attribute - some authorisation checks have to be performed in code that is called by controller methods - what is the correct way to return a 401 unauthorised response in this case?
我尝试过 throw new HttpException(401, "Unauthorized access");
,但是当我这样做时,响应状态代码是 500,我也得到了堆栈跟踪.即使在我们的日志记录 DelegatingHandler 中,我们也可以看到响应是 500,而不是 401.
I have tried throw new HttpException(401, "Unauthorized access");
, but when I do this the response status code is 500 and I get also get a stack trace. Even in our logging DelegatingHandler we can see that the response is 500, not 401.
推荐答案
你应该抛出一个 HttpResponseException
来自您的 API 方法,而不是 HttpException
:
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);
这篇关于ASP.NET Web API:返回 401/未授权响应的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!