是否可以通过物理路径为静态文件动态生成绝对或相对URL?无需任何硬编码。类似于UrlHelper对操作方法所做的操作。
例如,如果我有一条物理路径:
C:\some\path\outside\wwwroot\file.jpg
我如何获得此绝对路径:
https://localhost:9000/images/file.jpg
静态文件中间件的配置如下:
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(@"C:\some\path\outside\wwwroot"),
RequestPath = "/images"
}
答案 0 :(得分:0)
我已经设计出了一个相当精致而复杂的解决方案。
首先,在Startup.Configure
中,声明两个静态路径:
app.UseStaticFiles(new StaticFileOptions
{
RequestPath = "/images",
FileProvider = new PhysicalFileProvider(@"C:\some\path\outside\wwwroot"),
});
app.UseStaticFiles(new StaticFileOptions
{
RequestPath = string.Empty, // default behavior: static files from "/" (root)
FileProvider = new PhysicalFileProvider(env.WebRootPath),
});
第二,在Startup.ConfigureServices
中,为StaticFileOptions
路径注册/images
(要注入到控制器/视图中):
services.Configure<StaticFileOptions>(options =>
{
options.FileProvider = new PhysicalFileProvider(@"C:\some\path\outside\wwwroot");
options.RequestPath = "/images";
});
内部控制器:
// ...
private StaticFileOptions staticFileOptions;
public SomeController(IOptions<StaticFileOptions> fileOptions)
{
this.staticFileOptions = fileOptions.Value;
}
private string GetBaseUrl()
{
var request = this.Request;
var host = request.Host.ToUriComponent();
var pathBase = request.PathBase.ToUriComponent();
return $"{request.Scheme}://{host}{pathBase}";
}
// ...
public IActionResult Index()
{
const string physicalFile = @"C:\some\path\outside\wwwroot\generated-file.jpg";
// ... omitted: generate a file
var fileUrl = this.GetBaseUrl()
+ this.staticFileOptions.RequestPath.ToUriComponent()
+ (new PathString("/" + Path.GetFileName(physicalFile)).ToUriComponent());
ViewBag.GeneratedFileURL = fileUrl;
// ... use ViewBag.GeneratedFileURL in view as needed
return View();
}
其中一些可以包装在TagHelper中,使其更加整洁。