ASP.NET Core Static File- Session 8

Session8-ASp.NET Core Static File

In this session, we are going to talk about ASP.NET Core Static File and how we can use Static File in our ASP.NET Core Web App project. Generally, we called html, JavaScript, CSS, images files as Static File and by default they should be located in wwwroot folder to be served.

Static File Location

As above mentioned, static file should be located in wwwroot folder under main project folder. Also in some circumstances we can keep our static files in other folder name that we will explain this situation in the next session of this tutorial series.

We can create wwwroot folder by right clicking on our project name and from Add menu select New Folder sub-menu. Then rename the folder to wwwroot. Also, for better folder structure it is recommended to add some other folder under wwwroor folder to be used for images, CSS and JavaScript file (js). We explain this categorization in detail during this session video.

ASP.NET Core Static File Middleware

For serving static file in our Web App, we need to call some middleware. One of these middleware is UseStaticFile. Moreover, we can assign a file to be loaded as project startup file. For this purpose we need to have a file with below file naming and UseDefaultFiles middleware.

  • index.htm
  • index.html
  • default.htm
  • default.html

Just bear in mind to call UseDefaultFiles before UseStaticFile to achieve proper result as shown in below piece of code.

Furthermore, we can change default file name to our custom file name. To achieve this goal, we can use one of UseDefaultFiles overload version which accept DefaultFilesOptions. Thus, first of all we need DefaultFilesOptions object.

Then, we need to clear default file names.

and Add our custom name and pass in to UseDefaultFiles middleware

The total required code:

UseFileServer Middleware

We can use UseFileServer instead of both UseStaticFile and UseDefaultFiles. By adding UseFileServer to Configure method of Startup Class, static files are served and default html page with above mentioned naming will be loaded as startup. Having said that, it is possible to change default file name same as above procedure. But this time with UseFile Server overload and its option file FileServerOptions. The Instruction is very similar to UseDefaultFiles middle ware and you can see the changes in below code.

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


0 0 votes
Article Rating

Inline Feedbacks
View all comments