问题描述
当我尝试执行无效操作时,我想向客户端返回403 Forbidden.我需要使用什么方法?
I would like to return a 403 Forbidden to the client when trying to perform an invalid operation. What is the method I need to use?
我在Internet上进行了搜索,但仅在MVC 5中找到了这些内容:
I searched over the internet but I found only these for MVC 5:
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:
How to return 403 for IActionResult type:
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状态和 allow 进行响应时,ASP.NET Core的身份验证逻辑将使用其禁止的处理方式来处理响应逻辑(可以在您的Startup
类中进行配置,并且可能导致重定向到另一个页面),请使用:
When you want to respond with a HTTP 403 status and allow ASP.NET Core's authentication logic to handle the response with its forbidden handling logic (can be configured in your Startup
class, and may cause a redirect to another page), use:
return Forbid();
(与Unauthorized()
相同)
当您要使用来自API的HTTP 403状态代码响应并且不希望 ASP.NET Core身份验证逻辑执行任何重定向或其他操作时,请使用:
When you want to respond with a HTTP 403 status code from an API and do not want the ASP.NET Core authentication logic to perform any redirect or other action, use:
return StatusCode(403);
这篇关于如何在ASP.NET Core中将403禁止响应作为IActionResult返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!