如何生成静态文件的URL(就像ASP.NET Core UrlHelper对于操作方法一样)?

时间:2019-05-23 10:22:30

标签: c# asp.net-core asp.net-core-mvc

是否可以通过物理路径为静态文件动态生成绝对或相对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"
}

1 个答案:

答案 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中,使其更加整洁。