我不知道如何在 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);
}
}