如何在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
上述就是C#学习教程:如何在ASP.NET Core中将403 Forbidden响应作为IActionResult返回分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1008964.html