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

ASP.NET MVC 6修改未登录时默认跳转URL的方法

修改ASP.NET Core MVC默认登录跳转地址

ASP.NET Core的Cookie认证组件默认将未授权访问的跳转路径设为/Account/Login,你无需寻找这个默认值的声明位置,直接在Program.cs中通过配置覆盖即可,具体操作如下:

  • 配置自定义登录路径
    在Program.cs的服务注册环节,找到认证服务配置代码,添加AddCookie选项并指定LoginPath为你的登录页路径/home/index:

    builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(options =>
        {
            // 设置跳转至你的自定义登录页
            options.LoginPath = "/home/index";
            // 保留默认的ReturnUrl参数,框架会自动将原访问地址传递到登录页
            options.ReturnUrlParameter = "ReturnUrl";
        });
    
  • 确保中间件顺序正确
    认证中间件必须在授权中间件之前注册,否则配置不会生效:

    app.UseAuthentication();
    app.UseAuthorization();
    
  • 登录页处理ReturnUrl跳转
    在HomeController的登录方法中,接收returnUrl参数,登录成功后跳转回用户原本试图访问的页面:

    [HttpPost]
    [AllowAnonymous]
    public async Task<IActionResult> Index(LoginViewModel model, string returnUrl = null)
    {
        if (ModelState.IsValid)
        {
            // 替换为你的用户身份验证逻辑
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, model.Username)
            };
            var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
            var principal = new ClaimsPrincipal(identity);
            
            await HttpContext.SignInAsync(principal);
            
            // 验证ReturnUrl为本地地址,避免跳转攻击
            if (!string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            return RedirectToAction("Index", "Home");
        }
        // 验证失败,返回登录页
        return View(model);
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 06:45:34