Significance Of Middle-Ware In Asp.Net Core

Middle-Ware in Asp.Net Core By Sagar Jaybhay

In asp .net core Middle-ware play’s an important role in handling incoming and outgoing HTTP request. This is also used for authorization and authentication.

The main use of this is to set up the request processing pipeline. There are different kinds of middle-ware present in asp.net core.

  1. Log writing middle-ware
  2. Static file serve middle-ware
  3. Authentication and Authorization middle-ware.

This middle-ware pipeline decides or determines how the request is processing.

How middle-ware work in asp.net core?

Middle-ware is configured in the application startup class in the configured method. Configure method sets up the request processing pipeline of an application.

Middle-Ware 1- Asp.Net Core

Middle-ware component has access to incoming request and outgoing request. They might pass the request to next middle-ware for further processing.

Short-Circuit in Asp.Net Core

In this the middle-ware does not pass the request to next middle-ware and process that request by self and return the response.

Middle-Ware 2
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.Run(async (context) =>
            {
                await context.Response.WriteAsync(System.Diagnostics.Process.GetCurrentProcess().ProcessName);
            });

            app.Run(async (context) =>
            {
                await context.Response.WriteAsync(_config["SomeIncreptedKey"]);
            });
        }

Middle-ware component may skip or ignored incoming request and pass this to next middle-ware for processing.

Middle-Ware 3

Middle ware component are executed as they added In request processing pipeline. It may process the outgoing response. In below code, only one middle-ware is added.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

         
            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello Sagar Jaybhay!");
            });
        }

So all incoming request are handled by only this one middle-ware. In Asp.net core if you want to serve special files like HTML, CSS, js files, images so that they need to be in special folder wwwroot.

App.Run:

This method is an extension method and it is implemented in IApplicationBuilder interface.

public static void Run(this IApplicationBuilder app, RequestDelegate handler)

This is signature of the Run method and it takes the second parameter as RequestDelegate and which takes HttpContext as the parameter. So the context object has access to both request and response properties.

Terminal Middle-ware

This is the middle-ware that does not pass the request to next middle-ware.

App.Use:

This method takes 2 parameters. First is HTTP context and second is the next delegate. This delegate is used to call next middle-ware.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.Use(async (context,next) =>
            {
                await context.Response.WriteAsync("Hello Sagar Jaybhay");
                await next();
            });

            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello Sagar Jaybhay3");
            });
        }

How to Serve Static files in asp.net core?

To serve static files we need to add wwwroot folder first. And images, js, HTML and CSS files are placed into this folder. This folder is a content root folder. Placed this folder in the root of the project folder.

Next thing is that you need to include.

app.UseStaticFiles();

you which serve the static content. The default file name for application file is default.html, default.htm, index.htm, index.html. But for getting this default file you need to add another middle-ware i.e app.UseDefaultFiles(); In this, we need to add middle-ware in the correct order.

Middle-Ware 4
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseDefaultFiles();
            app.UseStaticFiles();            

            app.Use(async (context,next) =>
            {
                await context.Response.WriteAsync("Hello Sagar Jaybhay");
                await next();
            });

            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello Sagar Jaybhay3");
            });
        }

So in this UseDefaultFiles only say to add default files but to serve these pages on the web we need UseStaticFiles. So next question is how I add another file which has a different name not as per convention how to add this file.

UseDefaultFiles have an overloaded method which takes DefaultFilesOptions as a parameter so need to add this option like below.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            DefaultFilesOptions defaultFiles = new DefaultFilesOptions();
            defaultFiles.DefaultFileNames.Clear();
            defaultFiles.DefaultFileNames.Add("demo.html");
            app.UseDefaultFiles(defaultFiles);
            app.UseStaticFiles();            

            app.Use(async (context,next) =>
            {
                await context.Response.WriteAsync("Hello Sagar Jaybhay");
                await next();
            });

            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello Sagar Jaybhay3");
            });
        }
Middle-Ware 5

There is another way to add files UseFileServer method and need to pass filererveroptions to this method. But the advantage of this no need to use Staticfiles method.

   public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }                       

            FileServerOptions fileServer = new FileServerOptions();
            fileServer.DefaultFilesOptions.DefaultFileNames.Clear();
            fileServer.DefaultFilesOptions.DefaultFileNames.Add("demo.html");

            app.UseFileServer(fileServer);

            app.Use(async (context,next) =>
            {
                await context.Response.WriteAsync("Hello Sagar Jaybhay");
                await next();
            });

            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello Sagar Jaybhay3");
            });
        }

In most of the case, we use extension method names to add middle-ware in the request processing pipeline. The method name starts with Use. Example of this UseFileServer, UseStaticFiles.

DeveloperExceptionPage

To throw exception I write below code.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }                       
                   
                      

            app.Run(async (context) =>
            {
                throw new Exception("Error occured");
                await context.Response.WriteAsync("Hello Sagar Jaybhay3");
            });
        }
DeveloperExceptionPage

 By using this code this error page is I m getting and why I am getting this because I use middleware      app.UseDeveloperExceptionPage();

Because of this I am getting information about stack trace, query, cookies and headers. In this order is important if I use this below in configure method then the response will be a different one. You can customize the exception by using DeveloperExceptionPageOptions.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            DeveloperExceptionPageOptions pageOptions = new DeveloperExceptionPageOptions();
            pageOptions.SourceCodeLineCount = 10;
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage(pageOptions);
            }                       
                   
                      

            app.Run(async (context) =>
            {
                throw new Exception("Error occured");
                await context.Response.WriteAsync("Hello Sagar Jaybhay3");
            });
        }

I use SourceCodeLineCount property is used for to display no of line before and after exception occurred. You can pass this developeroption exception to UseDeveloperExcetpionPage and you can customize the output of this.

DeveloperExceptionPage 1

Sagar Jaybhay, from Maharashtra, India, is currently a Senior Software Developer. He has continuously grown in the roles that he has held in the more than seven years he has been with this company. Sagar Jaybhay is an excellent team member and prides himself on his work contributions to his team and company as a whole.

Related posts