[英]ASP.NET Core 2.2 - accessing the StaticFileOption RequestPath later in code
在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;
這可能嗎?
不能完全確定是否有可能,但是解決方法可以是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
屬性的類。
您可以嘗試使用services.Configure
配置StaticFileOptions
。
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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.