在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;
这可能吗?
答案 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)
您可以尝试将StaticFileOptions
和services.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);
}
}