隐藏

.Net 5/6.0 根目录静态文件设置

发布:2022/11/14 0:01:34作者:管理员 来源:本站 浏览次数:533

由于.net 5 添加静态文件中间件默认是wwwroot文件目录的访问。如果我想访问跟目录的文件应该怎么设置呢?


在项目根目录添加一个test1.txt文件:




在Startup.cs类文件的Configure方法中添加UseStaticFiles的设置,具体代码如下:


   // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.

           public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<Startup> logger)

           {

               if (env.IsDevelopment())

               {

                   app.UseDeveloperExceptionPage();

               }

   

               //使用静态文件访问中间件,默认可以访问wwwroot文件夹中的文件

               app.UseStaticFiles();

               //使用默认文件访问中间件,设置StaticFileOptions来实现访问项目根目录文件

               app.UseStaticFiles(new StaticFileOptions

               {

                   FileProvider = new PhysicalFileProvider(

                                    Path.Combine(env.ContentRootPath, "")),

                   RequestPath = ""

               });

   

               app.UseRouting();

   

               app.UseEndpoints(endpoints =>

               {

   

                   endpoints.MapGet("/", async context =>

                   {

                       await context.Response.WriteAsync("Hello World!");

   

                   });

   

               });

           }


F5运行程序,在浏览器中显示结果: