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

安装.NET 8后发布ASP.NET Core 7 MVC项目遇视图找不到问题

问题描述

安装.NET 8后,我的ASP.NET Core 7 MVC项目无法正常发布并运行。这些项目在Visual Studio调试模式下运行正常,但发布到IIS后就报错“找不到视图”。我已经尝试修改.csproj文件、添加builder.Services.AddControllersWithViews().AddRazorRuntimeCompilation();等多种方案,使用的是Visual Studio 17.9.1,在安装.NET 8之前没有出现过这个问题。

发布配置自上次正常运行后未更改,我已添加上述运行时编译代码,所有视图都设置为“内容”类型,还尝试过添加新视图、检查发布输出等操作,请问我遗漏了什么?

项目代码

.csproj 文件

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup Label="Globals">
    <SccProjectName>%24/BCC/yyy/yyyMvc</SccProjectName>
    <SccProvider>{4CA58AB2-18FA-4F8D-95D4-32DDF27D184C}</SccProvider>
    <SccAuxPath>xxx</SccAuxPath>
    <SccLocalPath>.</SccLocalPath>
  </PropertyGroup>

  <PropertyGroup>
    <TargetFramework>net7.0</TargetFramework>
    <AddRazorSupportForMvc>true</AddRazorSupportForMvc>
    <PreserveCompilationContext>true</PreserveCompilationContext>
    <MvcRazorCompileOnPublish>false</MvcRazorCompileOnPublish>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>
<PropertyGroup>
   <PreserveCompilationContext>true</PreserveCompilationContext>
</PropertyGroup>
  <ItemGroup>
    <PackageReference Include="ClosedXML" Version="0.102.1" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" Version="7.0.16" />
    <PackageReference Include="Microsoft.CodeAnalysis.Compilers" Version="4.8.0" />
    <PackageReference Include="Microsoft.Net.Compilers.Toolset" Version="4.8.0">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
    <PackageReference Include="NLog" Version="5.2.3" />
    <PackageReference Include="NLog.Web.AspNetCore" Version="5.3.3" />
    <PackageReference Include="tinysort" Version="3.2.5" />
  </ItemGroup>

  <ItemGroup>
    <ProjectReference Include="..\DataAccess\DataAccess.csproj" />
    <ProjectReference Include="..\ProjectBase\ProjectBase.csproj" />
  </ItemGroup>

</Project>

Program.cs 文件

using yyyMvc.Classes;
using yyyMvc.Middleware;
using Microsoft.Data.SqlClient;
using NLog;
using NLog.Web;
using ProjectBase;
using System.Data;

Logger logger = NLog.LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger();

try
{
    // *********************************
    // BUILDER
    // *********************************
    var builder = WebApplication.CreateBuilder(args);

    builder.Logging.ClearProviders();
    builder.Host.UseNLog();

    // Add services to the container.
    builder.Services.AddControllersWithViews().AddRazorRuntimeCompilation();
    
    // Session
    builder.Services.AddHttpContextAccessor();
    builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    builder.Services.AddScoped<SessionManager>();
    builder.Services.AddSession();

    // app settings
    builder.Services.Configure<ConfigWeb.AuthenticationSettings>(builder.Configuration.GetSection("AuthenticationSettings"));
    builder.Services.AddSingleton<IDbConnection>(db => new SqlConnection(
        builder.Configuration.GetSection("ConnectionStrings").GetValue<string>("Test") ?? 
            throw new Exception("Missing connection string")) { });
    builder.Services.Configure<ConfigWeb.LoggingSettings>(builder.Configuration.GetSection("LoggingSettings"));
    builder.Services.Configure<ConfigWeb.SiteSettings>(builder.Configuration.GetSection("SiteSettings"));

    // *********************************
    // APP
    // *********************************
    var app = builder.Build();

    // Error is first middleware
    app.UseMiddleware<ErrorHandlerMiddleware>();

    // Configure the HTTP request pipeline.
    if (!app.Environment.IsDevelopment())
    {
        app.UseExceptionHandler("/Home/Error");
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseCookiePolicy();

    // Get authentication prepared, with sessions
    app.UseSession();
    app.UseRouting();
    app.UseAuthentication();
    app.UseAuthorization();

    // Logging middleware, must be after Cookies / Session, must be before MVC routing
    ConfigWeb.LoggingSettings loggingSettings = new ConfigWeb.LoggingSettings();
    builder.Configuration.GetSection("LoggingSettings").Bind(loggingSettings);
    if (loggingSettings.DataViewLogging)
    {
        app.UseMiddleware<LoggingHandlerMiddleware>();
    }

    // No map MVC
    app.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");

    app.UseStaticFiles();
    app.Run();

}
catch (Exception ex)
{
    // NLog: catch setup errors
    logger.Error(ex, "Stopped program because of exception");
    throw;
}
finally
{
    // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
    NLog.LogManager.Shutdown();
}
排查与解决方案
  • 修正中间件顺序:你的Program.cs中app.UseStaticFiles()放在了路由配置之后,这会导致视图依赖的静态资源和视图文件无法被正确访问。将其移到路由配置之前,正确的中间件顺序如下:

    app.UseHttpsRedirection();
    app.UseStaticFiles(); // 调整到此处
    app.UseCookiePolicy();
    
    // 会话与认证相关中间件
    app.UseSession();
    app.UseRouting();
    app.UseAuthentication();
    app.UseAuthorization();
    
    // 日志中间件
    ConfigWeb.LoggingSettings loggingSettings = new ConfigWeb.LoggingSettings();
    builder.Configuration.GetSection("LoggingSettings").Bind(loggingSettings);
    if (loggingSettings.DataViewLogging)
    {
        app.UseMiddleware<LoggingHandlerMiddleware>();
    }
    
    // MVC路由配置
    app.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
    
    app.Run();
    
  • 强制指定.NET 7 SDK版本:安装.NET 8后,Visual Studio可能默认使用.NET 8 SDK构建.NET 7项目,引发兼容性问题。在项目根目录创建global.json文件,锁定使用.NET 7 SDK:

    {
      "sdk": {
        "version": "7.0.406", // 替换为你本地安装的.NET 7 SDK具体版本
        "rollForward": "latestPatch"
      }
    }
    
  • 检查IIS应用程序池配置:确保IIS站点对应的应用程序池选择.NET Core v7.0,而非.NET Core v8.0;同时确认服务器上已安装适配.NET 7的ASP.NET Core托管模块。

  • 验证视图文件的发布状态:右键项目→属性→发布→编辑配置文件→文件发布选项,确认勾选“保留现有文件”,且发布输出目录中存在所有.cshtml视图文件。若缺失,可在.csproj中添加以下配置强制包含视图:

    <ItemGroup>
      <Content Include="Views\**\*.cshtml">
        <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      </Content>
    </ItemGroup>
    
  • 优化运行时编译配置:当前全局启用Razor运行时编译可能在生产环境引发兼容性问题,建议仅在开发环境启用:

    if (builder.Environment.IsDevelopment())
    {
        builder.Services.AddControllersWithViews().AddRazorRuntimeCompilation();
    }
    else
    {
        builder.Services.AddControllersWithViews();
    }
    
  • 清理缓存重新发布:删除本地项目的bin、obj文件夹,以及IIS站点的发布目录,重新生成并发布项目,避免旧编译文件干扰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 16:45:54