的ASP.NET Web API:正确方法返回一个401 /未经授权的响应 [英] ASP.NET Web API : Correct way to return a 401/unauthorised response

查看:2192
本文介绍了的ASP.NET Web API:正确方法返回一个401 /未经授权的响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用OAuth /令牌身份验证来验证请求的MVC的WebAPI的网站。所有相关的控制器都具有正确的属性,认证工作确定。

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.

的问题是,不是所有的请求的所用的属性的范围来授权 - 一些授权检查有code是受控制器方法调用来执行 - 什么是返回一个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?

我曾尝试抛出新的HttpException(401,未经授权的访问); ,但是当我做这个响应状态code是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.

推荐答案

您应该抛出一个<一个href=\"https://msdn.microsoft.com/en-us/library/system.web.http.htt$p$psponseexception.aspx\"><$c$c>Htt$p$psponseException从您的API方法,而不是<一href=\"https://msdn.microsoft.com/en-us/library/system.web.httpexception.aspx\"><$c$c>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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆