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

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

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?
I searched over the internet but I found only these for 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();
    }
 }


Solutions/Answers:

Answer 1:

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

(same applies to Unauthorized())


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

Answer 2:

Alternative to MstfAsan’s answer is to use:

return Forbid();

It is a method on the controller base class that does the same thing.

Or

return StatusCode(403);

If you want to return a message, then you must use StatusCode.

Answer 3:

You can use return new ForbidResult(); Class declaration is

public class ForbidResult : ActionResult, IActionResult

For more spesific usages visit https://docs.microsoft.com/en-us/aspnet/core/api/microsoft.aspnetcore.mvc.forbidresult

Answer 4:

If you don’t return ActionResult for response, you can use the following code :

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

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

Our Awesome Tools

References