Advertisements

Middleware And Staticfiles in Asp.Net Core 1.0 – Part 1


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 :

app.Run(async (context) =>
            {
                await context.Response.WriteAsync(" Welcome to Dotnet Core !!");
                
            });

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 :

app.Use(async (context, next) =>
            {
                await context.Response.WriteAsync(" Hello World !!");
                await next.Invoke();//mandatory for invoking next delegates request
            });
            app.Run(async (context) =>
            {
                await context.Response.WriteAsync(" Welcome to Dotnet Core !!");
                
            });

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.

indexpage-rajeeshmenoth

Static File Example : Index Page in ASP.NET Core 1.0

HTML Index Page Code

Index Page Code

Index Page Html 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.

Default Output

Default Output

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”.

StaticFiles Configuration in Asp.Net Core 1.0

StaticFiles Configuration in Asp.Net Core 1.0

project.Json

Now Staticfiles version is updated in project.Json file.

{  
  "dependencies": {  
    "Microsoft.NETCore.App": {  
      "version": "1.0.1",  
      "type": "platform"  
    },  
    "Microsoft.AspNetCore.Diagnostics": "1.0.0",  
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",  
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.1",  
    "Microsoft.Extensions.Logging.Console": "1.0.0",  
    "Microsoft.AspNetCore.Mvc": "1.0.1",
    "Microsoft.AspNetCore.StaticFiles": "1.1.0"  // Staticfiles dependency 
  },  
   
  "tools": {  
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"  
  },  
   
  "frameworks": {  
    "netcoreapp1.0": {  
      "imports": [  
        "dotnet5.6",  
        "portable-net45+win8"  
      ]  
    }  
  },  
   
  "buildOptions": {  
    "emitEntryPoint": true,  
    "preserveCompilationContext": true  
  },  
   
  "runtimeOptions": {  
    "configProperties": {  
      "System.GC.Server": true  
    }  
  },  
   
  "publishOptions": {  
    "include": [  
      "wwwroot",  
      "web.config"  
    ]  
  },  
   
  "scripts": {  
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]  
  }  
}

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

app.UseDefaultFiles(); // Call first before app.UseStaticFiles()
app.UseStaticFiles(); // For the wwwroot folder

Output

Staticfile Output

Staticfile 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

DefaultFilesOptions DefaultFile = new DefaultFilesOptions();
            DefaultFile.DefaultFileNames.Clear();
            DefaultFile.DefaultFileNames.Add("Welcome.html");
            app.UseDefaultFiles(DefaultFile);
            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

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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: