我有一个MVC webapi站点,它使用OAuth/令牌身份验证来验证请求。所有相关控制器都具有正确的属性,并且身份验证工作正常。
问题是,并不是所有的请求都可以在属性的范围内被授权--一些授权检查必须在控制器方法调用的代码中执行--在这种情况下,返回401个未经授权的响应的正确方法是什么?
我尝试过throw new HttpException(401, "Unauthorized access");,但是当我这样做时,响应状态代码是500,我也得到了一个堆栈跟踪。即使在日志记录DelegatingHandler中,我们也可以看到响应是500,而不是401。
发布于 2015-07-03 12:26:20
您应该从API方法抛出一个HttpResponseException,而不是HttpException。
throw new HttpResponseException(HttpStatusCode.Unauthorized);或者,如果您想提供一个自定义消息:
var msg = new HttpResponseMessage(HttpStatusCode.Unauthorized) { ReasonPhrase = "Oops!!!" };
throw new HttpResponseException(msg);发布于 2016-08-01 20:39:39
只需返回以下内容:
return Unauthorized();发布于 2018-02-14 11:15:27
作为其他答案的替代方案,如果希望在IActionResult控制器中返回ASP.NET,也可以使用此代码。
ASP.NET
return Content(HttpStatusCode.Unauthorized, "My error message");更新: ASP.NET核心
以上代码在ASP.NET核心中不起作用,您可以使用其中之一:
return StatusCode((int)System.Net.HttpStatusCode.Unauthorized, "My error message");
return StatusCode(Microsoft.AspNetCore.Http.StatusCodes.Status401Unauthorized, "My error message");
return StatusCode(401, "My error message");显然,原因短语是相当可选的(Can an HTTP response omit the Reason-Phrase?)
https://stackoverflow.com/questions/31205599
复制相似问题