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

ASP.NET Core 2.1迁移3.1后找不到UserLogin视图求助

问题解决:ASP.NET Core 3.1迁移后找不到UserLogin视图

问题根源

核心错误是Cookie认证的LoginPath配置错误:你直接指定了视图文件的物理路径/Views/Logins/UserLogin.cshtml,但ASP.NET Core中LoginPath需要的是控制器Action的路由地址,而非视图文件路径。ASP.NET Core 3.1对路由和认证的处理更严格,2.1版本的兼容机制不再生效,导致请求直接访问视图文件路径时,框架无法正确匹配到控制器Action,进而找不到视图。

解决方案

1. 修正Cookie认证的LoginPath配置

修改Startup.cs中AddCookie的配置,将LoginPath改为控制器Action的路由:

.AddCookie(options =>
{
    // 替换为控制器Action路由,而非视图文件路径
    options.LoginPath = "/Logins/UserLogin";
    options.AccessDeniedPath = "/AccessDenied";
    options.ExpireTimeSpan = TimeSpan.FromHours(10);
});

2. 检查并调整中间件顺序

ASP.NET Core 3.1对中间件顺序要求严格,确保认证相关中间件顺序正确:

app.UseRouting();
app.UseAuthentication(); // 必须在UseAuthorization之前
app.UseAuthorization(); // 新增此中间件,确保授权逻辑依赖认证信息
app.UseSession();
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(name: "default", pattern: "{controller=UserProfiles}/{action=Index}/{id?}");
});

3. 规范UserProfilesController的重定向逻辑

确保UserProfilesController.Index通过[Authorize]特性触发自动重定向,避免手动指定错误路径:

public class UserProfilesController : Controller
{
    [Authorize] // 添加此特性,未登录时自动跳转到LoginPath配置的地址
    public IActionResult Index(int id)
    {
        // ... 你的业务逻辑
    }
}

验证修改

启动项目后,未登录用户访问UserProfiles/Index时,框架会自动重定向到/Logins/UserLogin,此时LoginsController.UserLogin方法会被调用,正确返回/Views/Logins/UserLogin.cshtml视图。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 08:00:54