ASP.NET Core 2.2-稍后在代码中访问StaticFileOption RequestPath

时间:2019-06-11 22:15:50

标签: asp.net-core asp.net-core-staticfile

在Startup.cs配置功能中,我这样做:

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

稍后,在控制器中说,我不想硬编码:

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

相反,我想做类似的事情:

        string ImageImLookingFor = SomeObjectThatGivesMe.RequestPath + foo.jpg;

这可能吗?

2 个答案:

答案 0 :(得分:2)

不确定是否可以,但是解决方法可以是appsettings键,并可以从两个位置读取它。

例如: 在您的应用设置中

{
 "ImagesPath" : '/images"
}

在Starup.cs

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

在您的控制器中

    string ImageImLookingFor = configuration.RequestPath + foo.jpg;

您可以使配置文件成为强类型,并用IOptions<ImageConfiguration>替换它,其中ImageConfiguration是具有ImagesPath属性的类

答案 1 :(得分:1)

您可以尝试将StaticFileOptionsservices.Configure配置为

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);            
    }
} 

然后通过IOptions<StaticFileOptions>

进行访问
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);
    }        
}