.NET Core3.0迁移至.NET6后布局及Identity视图缺失问题求助
.NET Core 3.0迁移至.NET6后的视图缺失与HTTPS问题解决
问题背景
将项目从.NET Core 3.0重构迁移至.NET6后,原项目仅能通过HTTP协议运行,无法使用HTTPS。创建新项目迁移原有文件后,运行应用时出现以下两个错误:
InvalidOperationException: The layout view '/views/shared/_Layout.cshtml' could not be located.InvalidOperationException: The default Identity UI layout requires a partial view '_LoginPartial' usually located at '/Pages/_LoginPartial' or at '/Views/Shared/_LoginPartial' to work. Based on your configuration we have looked at it in the following locations: /Areas/Identity/Pages/Account/_LoginPartial.cshtml /Areas/Identity/Pages/_LoginPartial.cshtml /Areas/Identity/Pages/Shared/_LoginPartial.cshtml /Areas/Identity/Views/Shared/_LoginPartial.cshtml /Pages/Shared/_LoginPartial.cshtml /Views/Shared/_LoginPartial.cshtml.
项目配置代码
var builder = WebApplication.CreateBuilder(args); // Add services to the container. var services = builder.Services; services.AddDbContext<GasdwahedDbContext>(options => { options.UseSqlServer( builder.Configuration.GetConnectionString("DefaultDbConnection")); options.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking); }); services.AddIdentity<ApplicationUser, IdentityRole>(options => { options.Password.RequireNonAlphanumeric = false; options.Password.RequireDigit = false; options.Password.RequireLowercase = false; options.Password.RequireUppercase = false; options.Password.RequiredLength = 6; }) .AddEntityFrameworkStores<GasdwahedDbContext>() .AddDefaultUI() .AddDefaultTokenProviders(); services.AddControllersWithViews(); services.AddMvc(options => options.EnableEndpointRouting = false); services.AddRazorPages(); services.AddScoped<IUserClaimsPrincipalFactory<ApplicationUser> , ApplicationUserClaimsPrincipalFactory>(); services.AddSignalR(); //services.Configure<ForwardedHeadersOptions>(options => //{ // options.KnownProxies.Add(IPAddress.Parse("192.168.1.220")); //}); services.Configure<TwilioVerifySettings>(builder.Configuration.GetSection("Twilio")); //JWT Generate Token var appSettingsSection = builder.Configuration.GetSection("AppSettings"); services.Configure<AppSettings>(appSettingsSection); var appSettings = appSettingsSection.Get<AppSettings>(); var key = Encoding.ASCII.GetBytes(appSettings.Secret); services.AddAuthorization(options => { options.AddPolicy("Admin", authBuilder => { authBuilder.RequireRole("Administrators"); }); }); services.AddAuthentication(x => { x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(x => { x.RequireHttpsMetadata = false; x.SaveToken = true; x.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(key), ValidateIssuer = false, ValidateAudience = false }; }); services.ConfigureApplicationCookie(options => { options.ExpireTimeSpan = TimeSpan.FromDays(5); }); var app = builder.Build(); // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseForwardedHeaders(new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto }); app.UseAuthentication(); app.UseAuthorization(); app.MapRazorPages(); app.MapControllerRoute( name: "MyArea", pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}"); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.Run();
解决方案
一、修复视图缺失问题
检查_Layout.cshtml文件
- 确认
/Views/Shared/_Layout.cshtml文件存在,若缺失,从原.NET Core 3.0项目复制或新建标准布局视图。 - 注意路径大小写:.NET6在大小写敏感的文件系统(如Linux)下严格匹配路径,确保路径与实际文件一致(例:
/Views/Shared/而非/views/shared/)。
- 确认
处理_LoginPartial缺失
- 若需Identity登录功能,在
/Views/Shared/目录创建_LoginPartial.cshtml,示例内容:@using Microsoft.AspNetCore.Identity @inject SignInManager<ApplicationUser> SignInManager @inject UserManager<ApplicationUser> UserManager @if (SignInManager.IsSignedIn(User)) { <form asp-area="" asp-controller="Account" asp-action="Logout" method="post" id="logoutForm" class="navbar-right"> <ul class="nav navbar-nav navbar-right"> <li> <a asp-area="" asp-controller="Manage" asp-action="Index" title="Manage">Hello @UserManager.GetUserName(User)!</a> </li> <li> <button type="submit" class="btn btn-link navbar-btn navbar-link">Logout</button> </li> </ul> </form> } else { <ul class="nav navbar-nav navbar-right"> <li><a asp-area="" asp-controller="Account" asp-action="Login">Login</a></li> <li><a asp-area="" asp-controller="Account" asp-action="Register">Register</a></li> </ul> } - 若不需要默认Identity UI,移除
AddIdentity链中的.AddDefaultUI(),改用自定义身份验证页面。
- 若需Identity登录功能,在
二、修复HTTPS无法运行问题
配置HTTPS端口与证书
- 检查
Properties/launchSettings.json,确保已配置HTTPS端口,示例:"profiles": { "YourProjectName": { "commandName": "Project", "dotnetRunMessages": true, "launchBrowser": true, "applicationUrl": "https://localhost:7123;http://localhost:5123", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } - 执行命令
dotnet dev-certs https --trust生成并信任开发环境HTTPS证书。
- 检查
调整中间件顺序
UseForwardedHeaders需放在UseRouting之前,否则无法正确识别代理传递的HTTPS信息,修正后代码:var app = builder.Build(); // 优先处理转发头 app.UseForwardedHeaders(new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto }); if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); // 路由映射代码...- 若部署在反向代理(如Nginx、IIS)后,启用
ForwardedHeaders并配置KnownProxies/KnownNetworks。
修正JWT配置
- 生产环境需将
x.RequireHttpsMetadata = true,确保JWT仅通过HTTPS传输,开发环境可暂时保持false。
- 生产环境需将
内容的提问来源于stack exchange,提问作者Mena Samer
相关产品推荐
相关产品推荐

