I quite despise redirecting to status code pages, I think if there's an error on a certain URL, the response should be returned to THAT URL. However ASP.NET redirects 403 responses to /Account/AccessDenied
. Is there a way to hook into the callback and return a view without redirecting?
So for exmaple if the user navigates to /admin
which requires the Administrator
role but they don't have it, the server will return my custom view without redirecting.
After trying all the possible code i found there is no way to restrict the redirect to the access denied page but as workaround you could write the custom response for:
builder.Services.AddAuthentication("MyCookieAuth")
.AddCookie("MyCookieAuth", options =>
{
options.LoginPath = "/Account/Login";
options.Events = new CookieAuthenticationEvents
{
OnRedirectToAccessDenied = context =>
{
// Prevent redirection when access is denied
context.Response.StatusCode = StatusCodes.Status403Forbidden;
return context.Response.WriteAsync("Access Denied: You do not have permission to access this resource.");
}
};
});