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

使用ASP.NET Identity时如何移除ReturnUrl参数避免二次重定向

ASP.NET Identity 去掉授权跳转ReturnUrl、避免二次重定向的解决方案

直接通过重写应用Cookie的跳转逻辑实现,不需要额外的中转Action,全程只有一次跳转,性能损耗为0。

配置代码放置位置

  • .NET 6 及以上版本:写在Program.cs的服务注册区域(var builder = WebApplication.CreateBuilder(args)之后、var app = builder.Build()之前)
  • .NET 5 及更早版本:写在Startup.cs的ConfigureServices方法中

完整配置代码

services.ConfigureApplicationCookie(options => 
{
    options.Events.OnRedirectToLogin = context =>
    {
        // 适配API请求:API类未授权返回401状态码,不做页面跳转
        if (context.Request.Path.StartsWithSegments("/api") 
            || context.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
        {
            context.Response.StatusCode = StatusCodes.Status401Unauthorized;
        }
        else
        {
            // 普通页面请求直接跳转首页,不会自动追加ReturnUrl参数
            context.Response.Redirect("/");
        }
        return Task.CompletedTask;
    };
});

配置完成后可以删除之前新增的NotSignedIn中转Action以及对应的路径配置。

补充:.AddCookie代码的适用场景

如果你是独立使用Cookie认证、没有接入Identity组件,才需要用这段链式配置,内部逻辑和上面完全一致:

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.Events.OnRedirectToLogin = /* 复用上面的跳转逻辑即可 */
    });

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 14:36:02