Part 10: Static Files in Asp.Net Core 3.1
In this article, we will discuss how to read static file from asp.net core application. Code is available on GitHub
By default, static file are not readable from asp.net core application. There are two conditions/rule we need to follow.
1. Add middleware UseStaticFiles in startup class
2. All static file should be in wwwRoot folder.
Letβs understand this with example, create asp.net core 3.1 application with name AccessStatcFiles.
Check default code of startup class, UseStaticFiles middleware is missing in configure method.
Add UseStaticFiles middleware in asp.net core application.
Add wwwRoot folder under project. Right click on project Add -> New folder.
Rename NewFolder with wwwRoot and all static files like Html, javascript, images, ..etc created under wwwRoot folder. Static file outside of this folder not accessible from asp.net core application.
Add html page with name Index
Add below highlighted html tag under Index.html or Index.html.
Run application with below URL.
In asp.net core Index.html or index.htm file is default file and asp.net core check if file available it shows by default. To achieve this add middleware UseDefaultFiles shown below. Make sure you follow UseStaticFiles middleware after UseDefaultFiles shown below else core application wonβt show index as default page.
Instead of writing two separate middleware, you can use only one middleware to achieve same purpose. UseFileserver combines functionality of UseDefaultFiles and UseStaticFiles middleware.
We discussed above asp.net core not served static files which
are not in wwwRoot folder. Its true by default asp.net core not support static
files outside wwwRoot folder, but you can achieve this by specifying path of
folder where you want to store static file.
Create folder in root directory of project with name Content or any name highlighted below. Create Sample.html file with some html tags and image file inside StaticFiles folder.
Modify UseFileServer middleware highlighted code shown below.
Run application with below URL highlighted.
Asp.Net core also provide feature to prefix some text before using actual file in URL. Like before (localhost:44392/StaticFiles/photo1.jpg). letβs check with an example
If you want to access static files from both folders (wwwRoot and StaticFiles), use below code highlighted.
5 Comments:
Very nice explained π
Thanks
Explained very well and in the step step by step with screenshots it is understanding correctly without writing the code.π
Thank you
Very good blog on static files...πππ
Post a Comment
Subscribe to Post Comments [Atom]
<< Home