Friday, January 29, 2016

Consuming Static Resources in ASP.NET Core 1.0

Exclusive Amazon Deals
As discussed in my previous article, static files are those files which are served directly to clients. It includes HTML, CSS, image and JavaScript files. In ASP.NET Core 1.0, default location of static files is wwwroot of project and location of this wwwroot is defined in project.json. So, all the static files which you want to serve to clients must be placed at wwwroot location.  

My article focuses on how to access and expose such static resources to client. Now let’s proceed step-by-step to create awareness on how to use static files.

Step 1 - Create an empty ASP.NET 5 project
Open Visual Studio 2015, select an empty project template for creating new ASP.NET application as:

 Step 2 – Introduce Static File
Create a HTML file under wwwroot folder. Below is my sample HTML file named SampleHTML:


Step 3 - Configure Middleware
Middleware are small components that can be combined as part of application in order to handle HTTP request response pipeline. So in order to serve static files. Midddleware has to be configured by adding static files to the pipeline. And this can be achieved by using extension method named UseStaticFiles in Startup class. But before that, add the required dependency in project.json file as highlighted below:



Next is to update Configure method in Startup class as:


Step 4 - Build and run
Build your code. Now type address as http://<your app name>/SampleHTML.html, your page will be rendered as:



Hope you enjoyed playing with static files. Benefit of using static files in such a way is that you need not to put extra effort to save your sensitive static file because if your file is not available at wwwroot, it won’t be rendered to client. Enjoy learning !!!

No comments:

Post a Comment