How to return 403 Forbidden Answer as IActionResult in ASP.NET Core

I want to return 403 Forbidden to the client when I try to perform an invalid operation. Which method do I need to use?

I searched over the Internet but found only for MVC 5:

If the return type for your web api method is HttpResponseMessage, then you need to use the code below:

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 type IActionResult:

public IActionResult Put(string userid, [FromBody]Setting setting)
 {
    var result = _SettingsRepository.Update(userid, setting);
    if (result == true)
    {
       return Ok(201);
    }
    else
    {
       return BadRequest();
    }
 }
+27
source share
4 answers

If you want to respond with HTTP status 403 and allow the authentication logic of ASP.NET Core to process the response using forbidden processing logic (it can be configured in your class Startupand can cause redirection to another page), use:

return Forbid();

( Unauthorized())


HTTP 403 API , ASP.NET Core , :

return StatusCode(403);
+45

MstfAsan :

return Forbid();

, .

return StatusCode(403);

, StatusCode.

+10

return new ForbidResult();

public class ForbidResult : ActionResult, IActionResult

For more frequent visits https://docs.microsoft.com/en-us/aspnet/core/api/microsoft.aspnetcore.mvc.forbidresult

+5
source

If you do not return ActionResultfor an answer, you can use the following code:

public List<SomeModel> get()
{
   ... 
   ... // check logic
   ...

   Response.StatusCode = 403;
   return new List<SomeModel>();
}
0
source

Source: https://habr.com/ru/post/1681426/


All Articles