2017-01-04 135 views
1

我试图提供在外部库内的静态文件。从外部库提供静态文件

我已经开始工作控制器和视图,但我无法从该库中加载资源(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 
      ) 
     }); 
    } 

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

"buildOptions": { 
    "emitEntryPoint": true, 
    "preserveCompilationContext": true, 
    "embed": [ 
     "Views/**/*.cshtml", 
     "wwwroot/**" 
    ] 
    }, 

谁能告诉我有什么不对?

谢谢大家(和抱歉,我的英语不好)

+1

时,可能是由于这样的事实,即你的资源是wwwroot文件夹内做到这一点只需填写RequestPath变量。尝试将其内容移至您的外部文库 – Tseng

+0

这对我来说已经奏效!谢谢! 但我仍然在寻找一种替代方案,但不将内容移到根目录,因为我想使用Bower作为外部插件。 任何我再次发布 –

+0

我不认为它可能,没有写你自己的提供者。 'EmbeddedFileProvider'似乎不支持它看起来像一个根路径https://github.com/aspnet/FileSystem/blob/rel/1.1.0/src/Microsoft.Extensions.FileProviders.Physical/PhysicalFileProvider.cs# L39这个根路径被设置为'PhysicalFileProvider'到'wwwroot',因为请求中间件不知道文件的位置。当你使用中间件时,只有不带'wwwroot'的路径被传递给中间件。 – Tseng

回答

3

我知道这是一个老问题,但我面临着同样的问题,我的解决方案是创建嵌入的文件提供传递参数增加外部组件和像“assemblyName.wwwroot”这样的字符串。

假设你的程序集的名称是PersonComponent

var personAssembly = typeof(PersonComponent.Program).GetTypeInfo().Assembly; 
    var personEmbeddedFileProvider = new EmbeddedFileProvider(
     personAssembly, 
     "PersonComponent.wwwroot" 
    ); 

然后,你必须使用此文件提供在UserStaticFiles呼叫

app.UseStaticFiles(); 
app.UseStaticFiles(new StaticFileOptions 
{ 
    FileProvider = personEmbeddedFileProvider 
}); 

Optionaly您可以使用其他的内容请求路径,因此您可以使用其他网址获取本地和外部资源。 要在创建StaticFileOptions

app.UseStaticFiles(); 
app.UseStaticFiles(new StaticFileOptions 
{ 
    FileProvider = personEmbeddedFileProvider, 
    RequestPath = new PathString("/external") 
}); 
+0

外部装配PersonComponent的静态文件夹的名称是什么? '\ wwwroot'或'\ external' – Jesus

+1

该文件夹的名称是** wwwroot **。 ** external **是一个路径字符串,您应该使用它来避免在不同项目中具有相同名称的静态文件时发生冲突。 例如,如果您的站点项目中有style.css,并且在PersonComponent中,则应使用** http://localhost/style.css**访问第一个,第二个使用路径字符串** http:/ /localhost/external/style.css** –