如何从DLL获取ASP.NET Core 6 MVC中的嵌入式资源文件
ASP.NET Core 6 MVC嵌入式资源访问问题
项目A配置
在Project A的ProjectA.csproj中添加以下配置,将wwwroot下所有文件标记为嵌入式资源,并设置静态资源基础路径:
<ItemGroup> <EmbeddedResource Include="wwwroot\**\*" /> </ItemGroup> <PropertyGroup> <StaticWebAssetBasePath Condition="$(StaticWebAssetBasePath) == ''">/path</StaticWebAssetBasePath> </PropertyGroup>
预期在其他项目中可以通过以下方式访问资源:
<link href="/path/css/siter.css" rel="stylesheet" />
嵌入式资源访问配置类
编写UIConfigureOptions类,实现IPostConfigureOptions<StaticFileOptions>来配置嵌入式资源的访问:
public class UIConfigureOptions : IPostConfigureOptions<StaticFileOptions> { public UIConfigureOptions(IHostingEnvironment environment) { Environment = environment; } public IHostingEnvironment Environment { get; } public void PostConfigure(string name, StaticFileOptions options) { name = name ?? throw new ArgumentNullException(nameof(name)); options = options ?? throw new ArgumentNullException(nameof(options)); options.ContentTypeProvider = options.ContentTypeProvider ?? new FileExtensionContentTypeProvider(); if (options.FileProvider == null && Environment.WebRootFileProvider == null) { throw new InvalidOperationException("Missing FileProvider."); } options.FileProvider = options.FileProvider ?? Environment.WebRootFileProvider; var basePath = "wwwroot"; var filesProvider = new ManifestEmbeddedFileProvider(GetType().Assembly, basePath); options.FileProvider = new CompositeFileProvider(options.FileProvider, filesProvider); } }
主项目ProjectMain的引用配置
在ProjectMain的program.cs中添加代码,引入Project A的控制器、模型并配置资源访问:
builder.Services.AddControllersWithViews(); ConfigureMvcParts(builder.Services, typeof(ProjectA.Areas.Sample.Controllers.HomeController)); builder.Services.ConfigureOptions(typeof(ProjectA.Models.UIConfigureOptions)); void ConfigureMvcParts(IServiceCollection services, Type containingClassType) { Assembly assembly = containingClassType.Assembly; AssemblyPart assemblyPart = new AssemblyPart(assembly); EmbeddedFileProvider fileProvider = new EmbeddedFileProvider(assembly); services.AddControllersWithViews().ConfigureApplicationPartManager(apm => apm.ApplicationParts.Add(assemblyPart)); services.Configure<MvcRazorRuntimeCompilationOptions>(options => options.FileProviders.Add(fileProvider)); }
问题现象
- 当通过添加项目引用引入
Project A时,资源链接<link href="/path/css/siter.css" rel="stylesheet" />可以正常访问; - 当直接添加
Project A的dll文件作为引用时,嵌入式资源无法正常访问。
另外,执行以下代码可以获取到所有嵌入式资源的名称列表,但无法实际访问这些资源:
string[] resourceNames = typeof(UIConfigureOptions).Assembly.GetManifestResourceNames();
内容的提问来源于stack exchange,提问作者Mishaa
相关产品推荐
相关产品推荐

