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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…