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

标签 c# asp.net-core

我想在尝试执行无效操作时向客户端返回 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/

相关文章:

c# - 将 4 个字节(从字符串格式)转换为一个 u32。 C 或 C#

c# - 错误的 XAML 仍然编译没有错误,然后在 Xamarin.Forms 项目中发生运行时错误

c# - 如何决定使用什么 - double 或十进制?

entity-framework - 术语 'scaffold-dbcontext' 未被识别为 cmdlet、函数、脚本文件或可操作程序的名称

asp.net-core - 如何自定义OpenIddict产生的授权错误?

asp.net-core - .NET Core 2、DI、配置文件

javascript - Aurelia - 无法使用 typescript skeeton 使 asp net core 工作

c# - 试图弄清楚这个数据库文件是否有压缩数据

c# - ListView - 将垂直网格线与标题分隔线对齐 - 让最后一列填充空间

asp.net - Asp.Core 中的模型绑定(bind)与继承