Middleware And Staticfiles In ASP.NET Core 1.0 - Part One

Introduction
We are all familiar with asp.net HttpHandler and HttpModules but unfortunately both are gone in Asp.Net Core 1.0. Don’t worry!! They are replaced with an efficient and easy-to-implement approach called “Middleware.” We can say reusable classes are middleware or middleware components.
 
In Asp.net HttpHandler and HttpModules are configured through webconfig but in Middleware they are configured via code rather than web.config. We can add the middleware components code in Startup.cs file in ASP.NET Core 1.0.
Before reading this article you must read the following article for Asp.Net Core knowledge.
Built-in Middleware
 
The following are the Built-in Middlewares in ASP.Net Core 1.0.

Single Request Delegate
  • app.Run
  • app.Use
app.Run
 
App.Run is a single request delegate that handles all requests. If you want to call the next delegate request then you can use next keyword in lambda expression. The Run method short circuits the pipeline or terminates the pipeline ( It will not call a next request delegate). Run method should only be called at the end of your pipeline or it will call at last. 
 
Example app.Run
  1. app.Run(async (context) =>  
  2.             {  
  3.                 await context.Response.WriteAsync(" Welcome to Dotnet Core !!");  
  4.                    
  5.             });  
app.Use
 
The following code clearly mentions that app.Run method should only be called at the end of your pipeline or it will be called last. App use will take care of the next delegate request with the help of  next
 
Example app.Use
  1. app.Use(async (context, next) =>  
  2.             {  
  3.                 await context.Response.WriteAsync(" Hello World !!");  
  4.                 await next.Invoke();//mandatory for invoking next delegates request  
  5.             });  
  6.             app.Run(async (context) =>  
  7.             {  
  8.                 await context.Response.WriteAsync(" Welcome to Dotnet Core !!");  
  9.                    
  10.             });  
StaticFiles
 
The new folder in ASP.NET Core is wwwroot and it stores all the StaticFiles in our project. The StaticFiles means that the HTML files, CSS files, image files, and JavaScript files which are sent to the users’ browsers should be stored inside the wwwroot folder. 
 
Startup Page
 
Right Click “wwwroot” and click Add -> New Item -> Click “Client-side” sub category and select HTML Page. 

 
HTML Index Page Code 

 
Output
 
When we run our application then you will get the following:  Why are our StaticFiles not running ? Because StaticFiles are placed inside the wwwroot and when we want to call those files in ASP.NET Core 1.0 then you must install the StaticFiles package manager for ASP.NET Core through NuGet.   


StaticFiles Configuration ASP.NET Core 1.0
 
Go to NuGet Package Manager and Type StaticFiles in “Browse” Category. Then it will display many staticfiles details but we need to choose and Install Microsoft.AspNetCore.StaticFiles

 
project.Json
 
Now Staticfiles version is updated in project.Json file.
  1. {    
  2.   "dependencies": {    
  3.     "Microsoft.NETCore.App": {    
  4.       "version""1.0.1",    
  5.       "type""platform"   
  6.     },    
  7.     "Microsoft.AspNetCore.Diagnostics""1.0.0",    
  8.     "Microsoft.AspNetCore.Server.IISIntegration""1.0.0",    
  9.     "Microsoft.AspNetCore.Server.Kestrel""1.0.1",    
  10.     "Microsoft.Extensions.Logging.Console""1.0.0",    
  11.     "Microsoft.AspNetCore.Mvc""1.0.1",  
  12.     "Microsoft.AspNetCore.StaticFiles""1.1.0"  // Staticfiles dependency   
  13.   },    
  14.       
  15.   "tools": {    
  16.     "Microsoft.AspNetCore.Server.IISIntegration.Tools""1.0.0-preview2-final"   
  17.   },    
  18.       
  19.   "frameworks": {    
  20.     "netcoreapp1.0": {    
  21.       "imports": [    
  22.         "dotnet5.6",    
  23.         "portable-net45+win8"   
  24.       ]    
  25.     }    
  26.   },    
  27.       
  28.   "buildOptions": {    
  29.     "emitEntryPoint"true,    
  30.     "preserveCompilationContext"true   
  31.   },    
  32.       
  33.   "runtimeOptions": {    
  34.     "configProperties": {    
  35.       "System.GC.Server"true   
  36.     }    
  37.   },    
  38.       
  39.   "publishOptions": {    
  40.     "include": [    
  41.       "wwwroot",    
  42.       "web.config"   
  43.     ]    
  44.   },    
  45.       
  46.   "scripts": {    
  47.     "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]    
  48.   }    
  49. }  
Extension Methods
 
We can add this following method in “Startup.Cs” and every extension method runs as a sequence.
  • UseStaticFiles()
  • UseDefaultFiles()
  • UseFileServer() 
UseStaticFiles()
 
We can call the UseStaticFiles extension method from Startup.Cs and it makes the files in web wwwroot or web root as servable.
 
Code
  1. app.UseDefaultFiles(); // Call first before app.UseStaticFiles()  
  2. app.UseStaticFiles(); // For the wwwroot folder  
Output 


UseDefaultFiles()
 
UseDefaultFiles must be called before UseStaticFiles to serve the default file in client-side browser. If you mention UseStaticFiles() method after UseDefaultFiles() then it will run UseStaticFiles() method as default and automatically terminate other files coming after UseStaticFiles() method.
 
UseDefaultFiles() will only search for the following files in "wwwroot". If any of the files are detected first in "wwwroot" then that file runs as default in client browser.
  • default.html
  • index.html
  • default.htm
  • index.htm
If you want to run other files as default then check the following code in Startup.Cs
 
Code
  1. DefaultFilesOptions DefaultFile = new DefaultFilesOptions();  
  2.             DefaultFile.DefaultFileNames.Clear();  
  3.             DefaultFile.DefaultFileNames.Add("Welcome.html");  
  4.             app.UseDefaultFiles(DefaultFile);  
  5.             app.UseStaticFiles();  
UseFileServer()
 
It combines the functionality of UseStaticFiles() and UseDefaultFiles(). So we can reduce the code and handle Staticfiles and Default Files as a single file. UseFileServer() will take care of the static file as the default start page.
 
Code
  1. app.UseFileServer(); // Combines UseStaticFiles() and UseDefaultFiles()  
Reference
Conclusion
 
We learned Middleware & Staticfiles in Asp.Net Core 1.0, and I hope you liked this article. Please share your valuable suggestions and feedback.

Up Next
    Ebook Download
    View all
    Learn
    View all