c# - UseStatusCodePagesWithReExecute 不适用于禁止 (403)

标签 c# asp.net-core error-handling

当我将 404 指定为 http 结果代码时,UseStatusCodePagesWithReExecute 按预期工作。

enter image description here

当我将 403 指定为 http 结果代码时,UseStatusCodePagesWithReExecute 未按预期工作。它以某种方式工作,就像我指定了 UseStatusCodePagesWithRedirects 一样。

enter image description here

对于 400-600 范围内的所有状态代码,我需要 UseStatusCodePagesWithReExecute 的行为,包括 403。

配置代码:

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    //...
    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
            {
                options.Cookie.HttpOnly = true;
                options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
                options.Cookie.SameSite = SameSiteMode.None;
                options.AccessDeniedPath = new PathString("/error/403/");
                options.LoginPath = "/account/signinrouter/";
            });
    //...
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
{
    //...
    app.UseStatusCodePagesWithReExecute("/error/{0}");
    //...
}

Action 代码:

public IActionResult NotFound()
{
    return base.NotFound();
}

public IActionResult Forbidden()
{
    return base.Forbid();
}

最佳答案

想通了,感谢@Kirk

将此代码添加到 AddCookie 即可。

options.Events.OnRedirectToAccessDenied = context =>
{
    context.Response.StatusCode = 403;

    return Task.CompletedTask;
};

这是原始的事件处理方法,我不关心Location头,所以我省略了相关代码,你可能不想。

public Func<RedirectContext<CookieAuthenticationOptions>, Task> OnRedirectToAccessDenied { get; set; } = (Func<RedirectContext<CookieAuthenticationOptions>, Task>) (context =>
{
    if (CookieAuthenticationEvents.IsAjaxRequest(context.Request))
    {
    context.Response.Headers["Location"] = (StringValues) context.RedirectUri;
    context.Response.StatusCode = 403;
    }
    else
    context.Response.Redirect(context.RedirectUri);
    return Task.CompletedTask;
});

关于c# - UseStatusCodePagesWithReExecute 不适用于禁止 (403),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56868673/

相关文章:

c# - 我有什么选择可以使这段代码线程安全?

c# - 使用 "multi-type"属性序列化 Json 对象

error-handling - 以干净有效的方式处理 Lua 错误

static string[] contains() (slooooow) 与 == 运算符的 C# 性能

c# - 使用正则表达式解码 FMD 条形码

c# - 无法解析 'Swashbuckle.AspNetCore.Swagger.ISwaggerProvider' 类型的服务

r - 制作一个矩阵列表,其中每个矩阵都是数据帧的一行

javascript - 如果服务器在后端或模板引擎中发生某些错误,请显示错误页面而不是错误

c# - 使用 C# mongodb 驱动程序取消设置多个属性

windows - 使用 Apache 在 Windows 上托管 ASP.NET Core