2

我不知道如何在 ASP Net Core 中提供指向文件的链接。我尝试使用PhyisicalFileProvider该类无济于事。

我想要的是

给定硬盘上的一个文件夹根目录,在接收到如下查询字符串时:/localFolder/test.txt我希望服务器发送一个Link,以便用户可以单击并获取文件test.txt

重要
不想发送文件,而是发送它的链接,所以他可以点击它并下载它。

我尝试过的

1.使用扩展方法IApplicationBuilder.Map将请求直接定向到文件。

2.使用扩展方法IApplicationBuilder.Map+添加中间件,虽然我不知道如何提供链接?(将其添加到响应正文中?)

启动

public void ConfigureServices(IServiceCollection collection)
{
      //i have also added the provider to the service collection to further inject it in the middleware 
       var phyisicalFileProvider = new PhysicalFileProvider(config.Storage.DocxFileRoot);
       services.AddSingleton<IFileProvider>(phyisicalFileProvider);
}
public void Configure()
{
  //scenario without middleware
   app.Map("/localfiles", x => 
         x.UseStaticFiles(new StaticFileOptions {
            FileProvider = new PhysicalFileProvider([some file root]),RequestPath ="/localfiles"}
           ));
   //scenario with middleware 
   app.Map("/localfiles",x=>
               x.UseMiddleware<FileWare>()
          );


   app.UseEndpoints(endpoints => {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=File}/{action=Index}/{id?}");
   });

}

中间件

public class FileWare
{
      private IFileProvider provider;
      private RequestDelegate next;

      public FileWare(RequestDelegate next,IFileProvider provider)
      { 
           this.provider=provider;
           this.next=next;
      }

      public async Task Invoke(HttpContext context)
      {
            var query = context.Request.Query;
            var path=query.First(x => x.Key == "path").Value;
            var fileInfo=this.provider.GetFileInfo(path);
            await fileInfo.CreateReadStream().CopyToAsync(context.Response.Body);
       }
}
4

1 回答 1

0

如果您只想在剃刀视图中获得链接,请单击该链接下载本地磁盘中的文件(例如C:\MyFolder),您可以按照以下步骤操作:

1.剃刀视图

<a asp-controller="File" asp-action="download" asp-route-path="C:\MyFolder\test.txt">Download</a>

2.文件控制器

public IActionResult Download([FromQuery]string path)
    {

        string fileName = "test.txt";

        byte[] fileBytes = System.IO.File.ReadAllBytes(path);

        return File(fileBytes, "application/force-download", fileName);
    }
于 2020-02-20T06:23:34.150 回答