ASP.NET Core 2.2 - accessing the StaticFileOption RequestPath later in code

457 Views Asked by At

In Startup.cs Configure function I do something like this:

        app.UseStaticFiles(new StaticFileOptions()
        {
            FileProvider = new PhysicalFileProvider(@"\\server\somepath\someimages"),
            RequestPath = "/images"
        });

Later, say in the controller, I'd like to not hard-code:

        string ImageImLookingFor = "/images" + foo.jpg;

Instead I'd like to do something like:

        string ImageImLookingFor = SomeObjectThatGivesMe.RequestPath + foo.jpg;

Is this possible?

2

There are 2 best solutions below

0
On

Not entirely sure if it is possible but a workaround can be an appsettings key and read it from both locations.

ex: in your appsettings

{
 "ImagesPath" : '/images"
}

in Starup.cs

   app.UseStaticFiles(new StaticFileOptions()
    {
        FileProvider = new PhysicalFileProvider(@"\\server\somepath\someimages"),
        RequestPath = Configuration["ImagesPath"]
    });

In your contorller

    string ImageImLookingFor = configuration.RequestPath + foo.jpg;

You can make the configuration file a strong type and replace it with IOptions<ImageConfiguration> where ImageConfiguration is a class that has ImagesPath property

1
On

You could try to configure StaticFileOptions with services.Configure like

public class Startup
{
    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<StaticFileOptions>(options => {
            options.FileProvider = new PhysicalFileProvider(@"xxx");
            options.RequestPath = "/images";
        });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {            
        app.UseStaticFiles(app.ApplicationServices.GetRequiredService<IOptions<StaticFileOptions>>().Value);            
    }
} 

And then access it by IOptions<StaticFileOptions> like

public class HomeController : Controller
{
    private readonly StaticFileOptions _options;
    public HomeController(IOptions<StaticFileOptions> options)
    {
        this.configuration = configuration;
        _serviceProvider = serviceProvider;
        _options = options.Value;
    }
    public IActionResult Index()
    {
        return Ok(_options.RequestPath);
    }        
}