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

.NET 7中如何通过反射获取Razor类库wwwroot静态文件列表?

在.NET 7中获取Razor类库wwwroot静态资源列表的解决方案

为什么GetManifestResourceNames()返回空数组?

Razor类库(RCL)中的wwwroot文件默认不会被标记为嵌入资源,而是以"内容文件"的形式被打包和发布,因此无法通过反射的GetManifestResourceNames()方法获取到这些文件的名称。

解决方案一:将wwwroot文件设置为嵌入资源

步骤1:修改RCL项目文件

在RCL的.csproj文件中添加以下配置,将wwwroot下的所有文件同时设置为嵌入资源和内容文件(确保主项目仍能通过_content/Plugins访问):

<ItemGroup>
  <EmbeddedResource Include="wwwroot\**\*" />
  <Content Include="wwwroot\**\*" CopyToPublishDirectory="PreserveNewest" />
</ItemGroup>

步骤2:通过反射获取嵌入资源列表

修改代码,过滤并转换wwwroot相关的嵌入资源:

using System.Reflection;
using System.Linq;

var assembly = Assembly.GetAssembly(typeof(MyClassInPlugins));
var assemblyName = assembly.GetName().Name;
// 过滤出wwwroot开头的嵌入资源并转换为相对路径格式
var wwwrootResources = assembly.GetManifestResourceNames()
    .Where(name => name.StartsWith($"{assemblyName}.wwwroot."))
    .Select(name => 
        name.Replace($"{assemblyName}.wwwroot.", "").Replace('.', '/')
    )
    .ToList();

解决方案二:直接读取程序集所在目录的wwwroot文件

如果不想修改嵌入资源设置,可以读取程序集所在目录下的wwwroot文件夹内容(注意此方法不适用于单文件发布场景):

using System.Reflection;
using System.IO;

var assembly = Assembly.GetAssembly(typeof(MyClassInPlugins));
// 获取程序集的本地路径
var assemblyPath = new Uri(assembly.CodeBase).LocalPath;
var wwwrootDirectory = Path.Combine(Path.GetDirectoryName(assemblyPath), "wwwroot");

List<string> wwwrootFiles = new();
if (Directory.Exists(wwwrootDirectory))
{
    // 获取wwwroot下所有文件的相对路径
    wwwrootFiles = Directory.GetFiles(wwwrootDirectory, "*", SearchOption.AllDirectories)
        .Select(file => Path.GetRelativePath(wwwrootDirectory, file))
        .ToList();
}

补充说明

如果是在ASP.NET Core Web应用中,也可以通过IWebHostEnvironment访问_content/Plugins目录下的文件,但这是基于Web应用的运行时文件系统,而非直接从程序集读取:

using Microsoft.AspNetCore.Hosting;

public class SomeService
{
    private readonly IWebHostEnvironment _env;

    public SomeService(IWebHostEnvironment env)
    {
        _env = env;
    }

    public List<string> GetPluginStaticFiles()
    {
        var pluginContentDir = Path.Combine(_env.WebRootPath, "_content", "Plugins");
        if (!Directory.Exists(pluginContentDir)) return new List<string>();

        return Directory.GetFiles(pluginContentDir, "*", SearchOption.AllDirectories)
            .Select(file => Path.GetRelativePath(pluginContentDir, file))
            .ToList();
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 00:52:19