在启动中.cs 配置函数 我做了这样的事情:
app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(@"\serversomepathsomeimages"),
RequestPath = "/images"
});
稍后,在控制器中说,我不想硬编码:
string ImageImLookingFor = "/images" + foo.jpg;
相反,我想做这样的事情:
string ImageImLookingFor = SomeObjectThatGivesMe.RequestPath + foo.jpg;
这可能吗?
不完全确定是否可能,但解决方法可以是应用程序设置键并从两个位置读取它。
前任:在您的应用中设置中
{
"ImagesPath" : '/images"
}
在斯塔普.cs
app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(@"\serversomepathsomeimages"),
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);
}
}