从外部库提供静态文件

L.B*_*ral 5 .net c# asp.net-core-mvc .net-core asp.net-core

我试图提供外部库中的静态文件。

我已经在处理控制器和视图,但我无法从该库加载资源(javascript、图像等)。

这是我的 Startup.cs

    public void ConfigureServices(IServiceCollection services)
    {
    //...
    var personAssembly = typeof(PersonComponent.Program).GetTypeInfo().Assembly;
    var personEmbeddedFileProvider = new EmbeddedFileProvider(
          personAssembly,
          "PersonComponent"
       );

     services
       .AddMvc()
       .AddApplicationPart(personAssembly)
       .AddControllersAsServices();

    services.Configure<RazorViewEngineOptions>(options =>
                {
                    options.FileProviders.Add(personEmbeddedFileProvider);
                });
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        //...
        var personAssembly = typeof(PersonComponent.Program).GetTypeInfo().Assembly;
        var personEmbeddedFileProvider = new EmbeddedFileProvider(
            personAssembly,
            "PersonComponent"
        );

        app.UseStaticFiles();
        //This not work
        app.UseStaticFiles(new StaticFileOptions
        {
            FileProvider = new CompositeFileProvider(
                personEmbeddedFileProvider
            )
        });
    }
Run Code Online (Sandbox Code Playgroud)

这里是我在外部库的 project.json 上的 buildOptions 设置:

"buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true,
    "embed": [
      "Views/**/*.cshtml",
      "wwwroot/**"
    ]
  },
Run Code Online (Sandbox Code Playgroud)

谁能告诉我出了什么问题?

谢谢大家(对不起,我的英语不好)

小智 9

我知道这是一个老问题,但我遇到了同样的问题,对我来说,解决方案是创建嵌入式文件提供程序,将外部程序集和字符串作为参数传递给"assemblyName.wwwroot"

假设您的程序集名称是PersonComponent

    var personAssembly = typeof(PersonComponent.Program).GetTypeInfo().Assembly;
    var personEmbeddedFileProvider = new EmbeddedFileProvider(
        personAssembly,
        "PersonComponent.wwwroot"
    );
Run Code Online (Sandbox Code Playgroud)

然后你必须在UserStaticFiles调用中使用这个文件提供者

app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = personEmbeddedFileProvider
});
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用替代内容请求路径,这样您就可以使用不同的 URL 获取本地和外部资源。为此,只需RequestPath在创建时填充变量StaticFileOptions

app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = personEmbeddedFileProvider,
    RequestPath = new PathString("/external")
});
Run Code Online (Sandbox Code Playgroud)