如何在ASP.NET Core中将403 Forbidden响应作为IActionResult返回

我想在尝试执行无效操作时向客户端返回403 Forbidden。 我需要使用的方法是什么?

我搜索了互联网,但我发现只有MVC 5:

如果您的web api方法的返回类型是HttpResponseMessage,那么您需要使用以下代码:

return Request.CreateErrorResponse(HttpStatusCode.Forbidden, "RFID is disabled for this site."); Or if the return type for your web api method is IHttpActionResult then you need to use the below code return StatusCode(HttpStatusCode.Forbidden,"RFID is disabled for this site."); 

如何为IActionResult类型返回403:

 public IActionResult Put(string userid, [FromBody]Setting setting) { var result = _SettingsRepository.Update(userid, setting); if (result == true) { return Ok(201); } else { return BadRequest(); } } 

当您希望以HTTP 403状态响应并允许 ASP.NET Core的身份validation逻辑使用其禁止处理逻辑处理响应(可以在您的Startup类中配置,并可能导致重定向到另一个页面),请使用:

 return Forbid(); 

(同样适用于Unauthorized()


如果要使用API​​中的HTTP 403状态代码进行响应,并且不希望 ASP.NET Core身份validation逻辑执行任何重定向或其他操作,请使用:

 return StatusCode(403); 

替代MstfAsan的答案是使用:

 return Forbid(); 

它是控制器基类上执行相同操作的方法。

要么

 return StatusCode(403); 

如果要返回消息,则必须使用StatusCode

你可以使用return new ForbidResult(); 类声明是

 public class ForbidResult : ActionResult, IActionResult 

有关更多特定用途,请访问https://docs.microsoft.com/en-us/aspnet/core/api/microsoft.aspnetcore.mvc.forbidresult