net core中启用指定目录浏览并且下载文件

 

 

builder.Services.AddDirectoryBrowser();

//打开日志文件目录浏览
app.UseFileServer(new FileServerOptions
{
FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "logs")),
RequestPath = "/logs",
EnableDirectoryBrowsing = true,
StaticFileOptions =
{
ServeUnknownFileTypes = true,
DefaultContentType = "application/octet-stream",
OnPrepareResponse = ctx =>
{
var filePath = ctx.File.PhysicalPath;
// 使用 Path.GetFileName 和 StartsWith + EndsWith 来确保只匹配日志文件
if (Path.GetFileName(filePath).StartsWith("log-", StringComparison.OrdinalIgnoreCase) && filePath.EndsWith(".txt", StringComparison.OrdinalIgnoreCase))
{
ctx.Context.Response.Headers["Content-Disposition"] = "attachment; filename=\"" + Path.GetFileName(filePath) + "\"";
}
}
}
});

 

 

访问  ip+/logs/logs

posted @ 2024-08-21 16:59  忙碌的蜗牛  阅读(97)  评论(0)    收藏  举报