RazorLight在Release模式构建时失效,报找不到Microsoft.AspNetCore.Antiforgery.dll
问题描述
本地运行正常,但Release模式构建时出现错误:
Cannot find reference assembly 'Microsoft.AspNetCore.Antiforgery.dll' file for package Microsoft.AspNetCore.Antiforgery System.InvalidOperationException: Cannot find reference assembly 'Microsoft.AspNetCore.Antiforgery.dll' file for package Microsoft.AspNetCore.Antiforgery
已配置的.csproj属性:
<PropertyGroup> <TargetFramework>net7.0</TargetFramework> <CopyRefAssembliesToPublishDirectory>false</CopyRefAssembliesToPublishDirectory> <MvcBuildViews>true</MvcBuildViews> <PreserveCompilationReferences>true</PreserveCompilationReferences> <PreserveCompilationContext>true</PreserveCompilationContext> </PropertyGroup>
Program.cs中包含代码:
builder.Services.AddRazorPages().AddRazorRuntimeCompilation();
疑问:PreserveCompilationReferences和PreserveCompilationContext配置无效,.NET 7是否是问题根源?
问题根源与解决方法
禁用Release模式下的
MvcBuildViews冲突
开启<MvcBuildViews>true</MvcBuildViews>会在构建时编译视图,但在Release模式下,结合CopyRefAssembliesToPublishDirectory=false会导致引用程序集被清理,RazorLight无法找到依赖的Microsoft.AspNetCore.Antiforgery.dll。
解决:针对Release模式单独关闭该配置,或调整复制逻辑:<PropertyGroup Condition="'$(Configuration)' == 'Release'"> <MvcBuildViews>false</MvcBuildViews> <!-- 若需保留视图编译,可改为: --> <!-- <CopyRefAssembliesToPublishDirectory>true</CopyRefAssembliesToPublishDirectory> --> </PropertyGroup>移除Release模式下的RazorRuntimeCompilation
AddRazorRuntimeCompilation()是开发环境的热重载工具,在Release模式下开启会额外引入编译依赖,和RazorLight的视图编译逻辑冲突。
解决:仅在开发环境启用该功能:var builder = WebApplication.CreateBuilder(args); builder.Services.AddRazorPages(); if (builder.Environment.IsDevelopment()) { builder.Services.AddRazorPages().AddRazorRuntimeCompilation(); }适配.NET 7的引用程序集特性
.NET 7对发布阶段的引用程序集清理逻辑更严格,PreserveCompilationReferences和PreserveCompilationContext无法覆盖视图编译场景。建议将RazorLight更新到适配.NET 7的最新稳定版本。显式安装依赖包
若以上方法无效,直接显式添加Microsoft.AspNetCore.Antiforgery包,确保构建时能找到该程序集:dotnet add package Microsoft.AspNetCore.Antiforgery
内容的提问来源于stack exchange,提问作者erikscandola

