.net 5/6 根目录静态文件设置
由于.net 5 添加静态文件中间件默认是wwwroot文件目录的访问。如果我想访问跟目录的文件应该怎么设置呢?
1.在项目根目录添加一个test1.txt文件
2.在Startup.cs类文件的Configure方法中添加UseStaticFiles的设置,具体代码如下
1 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 2 public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<Startup> logger) 3 { 4 if (env.IsDevelopment()) 5 { 6 app.UseDeveloperExceptionPage(); 7 } 8 9 //使用静态文件访问中间件,默认可以访问wwwroot文件夹中的文件 10 app.UseStaticFiles(); 11 //使用默认文件访问中间件,设置StaticFileOptions来实现访问项目根目录文件 12 app.UseStaticFiles(new StaticFileOptions 13 { 14 FileProvider = new PhysicalFileProvider( 15 Path.Combine(env.ContentRootPath, "")), 16 RequestPath = "" 17 }); 18 19 app.UseRouting(); 20 21 app.UseEndpoints(endpoints => 22 { 23 24 endpoints.MapGet("/", async context => 25 { 26 await context.Response.WriteAsync("Hello World!"); 27 28 }); 29 30 }); 31 }
3.F5运行程序,在浏览器中显示结果