Serve Static Files Outside wwwroot in ASP.NET Core – Session 9

Session9 Serve Static Files Outside w w w r o o t ASP.NET Core

In this session we show you how ASP.NET Core Web App can serve Static Files outside of wwwroot folder. By default, Static Files should be located in wwwroot folder in ASP.NET Core Web App project which was described in Session 8 of this tutorial series.

How to Serve Static Files Outside wwwroot in ASP.NET Core

  • Step1: Create a custom folder under your project’s root folder
  • Step2: Create an object of StaticFilesOptions if you use UseStaticFiles or create an object of FileServerOptions if you use UseFileServer.
  • Step3: Add Microsoft.Extensions.FileProviders namespace to Startup Class
  • Step4: Add System.IO namespace to Startup Class
  • Step5: Define newly created folder via FileProvider
  • Step6: Use proper middleware overload version
  • Step7: Pass created Option object to the middleware

Static File Outside wwwroot with UseStaticFiles Middleware

Regardless of your middleware, first of all you need to create a folder under your project’s root with the name that you want. Then if you call UseStaticFiles middleware to serve your static files you need an object of StaticFileOptions. Through this object you can introduce new created folder to be static files container. Also, for this purpose and implementation of below piece of code, you need to import Microsoft.Extensions.FileProviders and System.IO namespace to your project Startup Class.

By above change, your default Static File container (wwwroot) will not be available anymore. Hence, for solving this issue and having both folder available for Static Files, you need to add one more UseStaticFiles middleware as you can see in below piece of code.

Static File Outside wwwroot with UseFileServer Middleware

Implementation of this change for UseFileServer Middleware is almost same as UseStaticFiles middleware. Just you need to create an object of FileServerOptions instead of StaticFileOptions. Then the rest of steps are same as each other as you can see in below code.

Also as you review above code for having access to both static files containers (wwwroot and newly created folder), we need to add UseFileServer middleware.

If you need more details, watch this session video. Also, for being updated about our coming sessions, follow us on Instagram, Facebook, Telegram or YouTube and be in touch with us here.

You can download this Session Slides form HERE

0.00 avg. rating (0% score) - 0 votes

Tags

0 0 votes
Article Rating
guest

0 Comments
Inline Feedbacks
View all comments