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

ASP.NET MVC登录成功后重定向至Razor页面的实现疑问

ASP.NET Core 登录成功后重定向至指定Razor页面解决方案

核心问题排查与修复

  • 修复Login方法逻辑错误:你当前代码中的if (adminInDb == null && HashGenerator.VerifyHash(...))判断完全颠倒,必须改为adminInDb != null && HashGenerator.VerifyHash(...),启用你注释掉的那段正确逻辑:

    [HttpPost("adminLogin")]
    public IActionResult Login(LoginInfo login)
    {
        Admin adminInDb = _context.Admins.FirstOrDefault(admin => admin.Username == login.Username);
    
        if (adminInDb != null && HashGenerator.VerifyHash(adminInDb.Password, login.Password, adminInDb.Salt))
        {
            return RedirectToPage("/admin");
            // 若为AJAX调用,可返回Ok(new { redirectUrl = "/admin" }),由前端处理跳转
        }
    
        return Unauthorized();
    }
    
  • 区分Web API与MVC控制器:你的AdminController标记了[ApiController],这是Web API专用控制器,默认返回JSON响应,RedirectToPage无法触发浏览器自动重定向。如果是服务器端表单提交登录,需移除[ApiController]和[Route("api/[controller]")],改用MVC控制器路由;如果是前端AJAX调用,登录接口应返回跳转地址,由前端通过window.location.href完成跳转。

Razor页面必须配置代码后置类(admin.cshtml.cs)

因为你的Razor页面使用了Model.Users,必须创建对应的代码后置类提供模型数据,否则页面会报错:

using Microsoft.AspNetCore.Mvc.RazorPages;
using YourAppNamespace; // 替换为你的AppContext所在命名空间

public class AdminModel : PageModel
{
    private readonly AppContext _context;

    public AdminModel(AppContext context)
    {
        _context = context;
    }

    public List<User> Users { get; set; } // 替换为你的用户实体类

    public void OnGet()
    {
        Users = _context.Users.ToList();
    }
}

Program.cs 关键配置

确保项目正确注册Razor Pages服务和中间件:

  1. 注册Razor Pages服务:
    builder.Services.AddRazorPages();
    
  2. 配置JWT认证(若使用):
    builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,
                ValidIssuer = JwtConfiguration.ValidIssuer,
                ValidAudience = JwtConfiguration.ValidAudience,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(JwtConfiguration.IssuerSigningKey))
            };
        });
    
    builder.Services.AddAuthorization();
    
  3. 中间件顺序必须严格遵循以下顺序:
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    
    app.UseRouting();
    
    app.UseAuthentication();
    app.UseAuthorization();
    
    app.MapRazorPages(); // 必须在授权中间件之后添加
    app.MapControllers();
    

额外注意事项

  • Razor页面默认存放在项目根目录的Pages文件夹下,你的admin.cshtml需要放在该文件夹内,RedirectToPage("/admin")才能正确定位页面。
  • 若为AJAX登录场景,不要在API控制器中使用RedirectToPage,应返回包含跳转地址的JSON响应,前端接收到后执行跳转:
    return Ok(new { redirectUrl = "/admin" });
    
    前端示例(JavaScript):
    fetch('/api/Admin/adminLogin', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(loginData)
    })
    .then(res => res.json())
    .then(data => {
        if (data.redirectUrl) {
            window.location.href = data.redirectUrl;
        }
    });
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 13:17:07