How to return 403 Forbidden response as IActionResult in ASP.NET Core
Simply you can use ObjectResult to return a custom response with a status code.
See the syntax,
return new ObjectResult("Message") {StatusCode = YOUR_STATUS_CODE };
Note - You can pass an object also,
return new ObjectResult(your_model) {StatusCode = YOUR_STATUS_CODE };
Example:
public async Task<IActionResult> Post([FromBody] SomeData _data)
{
// do your stuff
// return forbidden with custom message
return new ObjectResult("Forbidden") { StatusCode = 403};
}
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
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);
// 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.
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
.