C# 如何在ASP.NET Core 2中抛出禁止异常,而不是使用AccessDeniedPath
我正在开发一个ASP.NET Core 2 web应用程序。我正在处理[授权(角色或策略)]页面的访问被拒绝页面 默认情况下,ASP.NET Core 2.0不会显示原始URL并返回403状态,而是将请求重定向到状态为302->的AccessDenied页面,这不是我想要的 而不是重定向AccessDenied页面。我希望ASP.NET Core抛出我的自定义禁止异常异常,这样我就可以像处理未经处理的异常一样处理未经授权的访问 以下是我的身份验证配置:C# 如何在ASP.NET Core 2中抛出禁止异常,而不是使用AccessDeniedPath,c#,asp.net-core,asp.net-core-2.0,authorize-attribute,asp.net-authorization,C#,Asp.net Core,Asp.net Core 2.0,Authorize Attribute,Asp.net Authorization,我正在开发一个ASP.NET Core 2 web应用程序。我正在处理[授权(角色或策略)]页面的访问被拒绝页面 默认情况下,ASP.NET Core 2.0不会显示原始URL并返回403状态,而是将请求重定向到状态为302->的AccessDenied页面,这不是我想要的 而不是重定向AccessDenied页面。我希望ASP.NET Core抛出我的自定义禁止异常异常,这样我就可以像处理未经处理的异常一样处理未经授权的访问 以下是我的身份验证配置: services.AddAuthentic
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; // Cookies
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; // Cookies
options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme; // Cookies
})
.AddCookie(options => {
options.LoginPath = "/Auth/Login/";
options.LogoutPath = "/Auth/Logout/";
// I want disable this and throw ForbiddenException instead.
options.AccessDeniedPath = "/Auth/AccessDenied/";
});
有人能帮忙吗?谢谢大家! 重定向到
AccessDeniedPath
的代码由处理,为完整起见,包含在此处:
public Func<RedirectContext<CookieAuthenticationOptions>, Task> OnRedirectToAccessDenied { get; set; } = context =>
{
if (IsAjaxRequest(context.Request))
{
context.Response.Headers["Location"] = context.RedirectUri;
context.Response.StatusCode = 403;
}
else
{
context.Response.Redirect(context.RedirectUri);
}
return Task.CompletedTask;
};
这里,context
是的一个实例,它(通过其继承树)包含以下属性:
HttpContext
请求
响应
(类型:)属性
services.AddAuthentication(...)
.AddCookie(options => {
// ...
options.Events.OnRedirectToAccessDenied = context => {
// Your code here.
// e.g.
throw new YouAreNotWelcomeHereException();
};
});