我想在尝试执行无效操作时向客户端返回 403 Forbidden。我需要使用什么方法?
我在互联网上搜索过,但只找到了 MVC 5 的这些:
If the return type for your web api method is HttpResponseMessage then you need to use the below code:
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.");
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 状态并允许 ASP.NET Core 的身份验证逻辑使用其禁止的处理逻辑来处理响应时(可以在您的启动
类,并可能导致重定向到另一个页面),使用:
return Forbid();
(同样适用于 Unauthorized()
)
当您想使用来自 API 的 HTTP 403 状态代码进行响应并且不希望 ASP.NET Core 身份验证逻辑执行任何重定向或其他操作时,请使用:
return StatusCode(403);
// or with developer-friendly type
return StatusCode(StatusCodes.Status403Forbidden);
// or as an api-friendly error response
return Problem(
type: "/docs/errors/forbidden",
title: "Authenticated user is not authorized.",
detail: $"User '{user}' must have the Admin role.",
statusCode: StatusCodes.Status403Forbidden,
instance: HttpContext.Request.Path
);
后一个例子产生一个 client error response .
关于c# - 如何在 ASP.NET Core 中返回 403 Forbidden 响应作为 IActionResult,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45095853/