Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/329.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在ASP.NET Core 2中抛出禁止异常,而不是使用AccessDeniedPath_C#_Asp.net Core_Asp.net Core 2.0_Authorize Attribute_Asp.net Authorization - Fatal编程技术网

C# 如何在ASP.NET Core 2中抛出禁止异常,而不是使用AccessDeniedPath

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

我正在开发一个ASP.NET Core 2 web应用程序。我正在处理[授权(角色或策略)]页面的访问被拒绝页面

默认情况下,ASP.NET Core 2.0不会显示原始URL并返回403状态,而是将请求重定向到状态为302->的AccessDenied页面,这不是我想要的

而不是重定向AccessDenied页面。我希望ASP.NET Core抛出我的自定义禁止异常异常,这样我就可以像处理未经处理的异常一样处理未经授权的访问

以下是我的身份验证配置:

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