MVC控制器中的List ____()应该返回给用户什么未经授权?

时间:2019-03-03 18:35:31

标签: c# asp.net-mvc

所以我的StuffController.cs中有这段代码

[HttpGet, Route]
[Authorize(nameof(Access))]
public async Task<ActionResult> ListStuff()
{
    var canRead = HasAccess(new AccessLevels
    {
        Stuff = AccessLevel.Read
    });
}

由于此函数的返回类型为ActionResult,如果'canRead'为false,它将返回什么?理想情况下,我希望它显示一条消息(例如“您未经授权,请先征得管理员的同意”),如果用户试图转到此页面但没有授权。

1 个答案:

答案 0 :(得分:0)

401是未经授权的响应的状态码。

一种可能的解决方案是使用以下消息将401状态代码引发异常:

throw new HttpResponseException(
  new HttpResponseMessage(HttpStatusCode.Unauthorized)
   { 
      ReasonPhrase = "You're unauthorized, please ask admin for approval" 
   });

另一种解决方案:

return new HttpStatusCodeResult(401, "You're unauthorized, please ask admin for approval");

另一个:

Response.StatusCode = 401;
return Content("You're unauthorized, please ask admin for approval");