新建一个WebApi项目
进入Startup.cs文件,添加如下代码.
1app.UseFileServer(new FileServerOptions() {
2 // 文件提供路径
3 FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(),"StaticFile")),
4 RequestPath="", // 直接根目录就可以访问静态文件
5 EnableDefaultFiles = true // 默认访问 静态文件里面 index.html 文件
6 });
文件下载
1private readonly string _path;
2public WeatherForecastController(string path)
3{
4 this._path = path;
5}
6
7[HttpGet]
8public FileContentResult Get()
9{
10 var data = System.IO.File.ReadAllBytes(_path); // 其中path 由构造函数传入
11 var result = new FileContentResult(data, "application/octet-stream")
12 {
13 FileDownloadName ="File.txt"
14 };
15 return result;
16}
17// 构造函数传入指定路径
18services.AddSingleton(Path.Combine(Directory.GetCurrentDirectory(), "StaticFile", "File.txt"));