You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何移除ASP.NET Core Identity 403页面的查询字符串

移除403页面的ReturnUrl查询字符串

方法一:重写Cookie认证的访问拒绝跳转逻辑

这是最直接的方案,因为ASP.NET Core Identity的Cookie认证默认会在跳转到403页面时附加ReturnUrl,只需重写对应的事件即可:

在Program.cs中配置ConfigureApplicationCookie,修改访问拒绝时的跳转行为:

builder.Services.ConfigureApplicationCookie(options =>
{
    options.LoginPath = "/Identity/Account/Login";
    options.LogoutPath = "/Identity/Account/Logout";
    options.AccessDeniedPath = "/Error/403"; // 你的403页面路径

    // 重写访问拒绝的跳转逻辑,移除ReturnUrl
    options.Events = new CookieAuthenticationEvents
    {
        OnRedirectToAccessDenied = context =>
        {
            context.Response.Redirect(options.AccessDeniedPath);
            return Task.CompletedTask;
        }
    };
});

方法二:全局自定义授权结果处理器

如果需要更灵活的授权失败处理(比如区分不同授权策略的失败场景),可以实现自定义的IAuthorizationMiddlewareResultHandler:

  1. 注册自定义处理器到DI容器:
builder.Services.AddScoped<IAuthorizationMiddlewareResultHandler, CustomAuthorizationResultHandler>();
  1. 实现处理器逻辑:
public class CustomAuthorizationResultHandler : IAuthorizationMiddlewareResultHandler
{
    private readonly AuthorizationMiddlewareResultHandler _defaultHandler = new();

    public async Task HandleAsync(RequestDelegate requestDelegate, HttpContext httpContext, AuthorizationPolicy policy, PolicyAuthorizationResult authorizeResult)
    {
        // 仅处理授权拒绝的情况
        if (authorizeResult.Forbidden)
        {
            // 直接跳转403页面,不携带任何查询参数
            httpContext.Response.Redirect("/Error/403");
            return;
        }

        // 其他授权结果使用默认处理逻辑
        await _defaultHandler.HandleAsync(requestDelegate, httpContext, policy, authorizeResult);
    }
}

方法三:用中间件拦截跳转请求

编写一个中间件,在响应发送前检查是否是跳转到403页面的请求,若存在ReturnUrl则移除:

在Program.cs中添加该中间件(注意要放在授权中间件之前):

app.Use(async (context, next) =>
{
    await next();

    // 拦截302跳转且目标是403页面的请求
    if (context.Response.StatusCode == StatusCodes.Status302Found)
    {
        var location = context.Response.Headers.Location.ToString();
        if (location.StartsWith("/Error/403") && location.Contains("ReturnUrl"))
        {
            // 截取不带查询参数的基础路径
            var cleanUrl = location.Split('?')[0];
            context.Response.Headers.Location = cleanUrl;
        }
    }
});

// 确保授权中间件在该拦截中间件之后
app.UseAuthorization();

内容的提问来源于stack exchange,提问作者lonix

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 12:57:40