Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serve Static Files from External Library

I was trying to serve static files that was inside an external library.

I'm already do to work Controller and Views, but i'm not able to load the resources (javascript, images, ...) from that library.

Here is my 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
            )
        });
    }

And here my buildOptions settings on project.json of External Library:

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

Can anyone tell me what's wrong?

Thank you all (and sorry my bad english)

like image 463
L.Barral Avatar asked Jan 04 '17 15:01

L.Barral


1 Answers

I know this is an old question but i faced the same problem and for me the solution was to create the embedded file provider passing as parameters the external assembly and a string like "assemblyName.wwwroot".

Assuming that your assembly name is PersonComponent

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

Then you have to use this file provider in UserStaticFiles call

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

Optionaly you can use an alternative content request path, so you can get your local and external resources using a different URL. To do this just fill RequestPath variable when creating StaticFileOptions

app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = personEmbeddedFileProvider,
    RequestPath = new PathString("/external")
});
like image 181
Pablo García Avatar answered Sep 23 '22 03:09

Pablo García