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服务和中间件:
- 注册Razor Pages服务:
builder.Services.AddRazorPages(); - 配置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(); - 中间件顺序必须严格遵循以下顺序:
app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.MapRazorPages(); // 必须在授权中间件之后添加 app.MapControllers();
额外注意事项
- Razor页面默认存放在项目根目录的
Pages文件夹下,你的admin.cshtml需要放在该文件夹内,RedirectToPage("/admin")才能正确定位页面。 - 若为AJAX登录场景,不要在API控制器中使用
RedirectToPage,应返回包含跳转地址的JSON响应,前端接收到后执行跳转:
前端示例(JavaScript):return Ok(new { redirectUrl = "/admin" });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
相关产品推荐
相关产品推荐

