如何在 ASP.NET Core 中将 403 Forbidden 响应作为 IActionResult 返回 [英] How to return 403 Forbidden response as IActionResult in ASP.NET Core

查看:91
本文介绍了如何在 ASP.NET Core 中将 403 Forbidden 响应作为 IActionResult 返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我在互联网上进行了搜索,但我只找到了这些适用于 MVC 5 的内容:

I searched over the internet but I found only these for MVC 5:

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

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.");

如何为 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 状态响应并允许 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);

// 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
);

后一个例子产生一个 客户端错误响应.

The latter example produces a client error response.

这篇关于如何在 ASP.NET Core 中将 403 Forbidden 响应作为 IActionResult 返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆