UseStatusCodePagesWithReExecute不适用于禁止(403)

时间:2019-07-03 11:02:22

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

当我将404指定为http结果代码时,UseStatusCodePagesWithReExecute的工作正常。

enter image description here

当我将403指定为http结果代码时,UseStatusCodePagesWithReExecute无法正常工作。就像我指定了UseStatusCodePagesWithRedirects一样。

enter image description here

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

配置代码:

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}");
    //...
}

操作代码:

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

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

1 个答案:

答案 0 :(得分:1)

弄清楚了,多亏@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;
});