ttmind

Main Navigation

ttmind
  • jim-jams
  • Tech
  • Positive
Login

Login

Facebook Google

OR

Remember me Forgot password?

Don't have account? Signup here.

Sort by Categorys

.Net

PHP

Java

JavaScript

Database

Server

Client Side

Tools

Artificial Intelligence

Cloud

Hybrid Development

Event

Smart City

Education

Security

Scrum

Digital Marketing

APP Development

Business

Internet

Simulation

Art

Network

Microservices

Architecture

Technology

Leadership

    Top Articles

  • How Does Social Media Bring People Together?
    TTMind Author
  • How to read appSettings JSON from Class Library in ASP.NET Core
    Anil Shrestha
  • Printing Support In Asp.Net Core
    TTMind Author
  • HOW TO EXTRACT TEXT FROM IMAGE USING JAVASCRIPT (OCR with Tesseract.js)?
    Prakash Pokhrel
  • Images Upload REST API using ASP.NET Core
    Prakash Pokhrel
  • Related Topic

  • How to read appSettings JSON from Class Library in ASP.NET Core
  • Printing Support In Asp.Net Core
  • Images Upload REST API using ASP.NET Core
  • How to use IActionFilter, IAsyncActionFilter in ASP.NET Core MVC?
  • ASP.NET CORE - Blazor CRUD operation using ADO.NET
  • Tech
  • About Us
  • Contact Us
  • TechHelp
  • PositiveHelp
  • Jim-Jams Help
  • Terms & Conditions

© Copyright ttmind.com

Main Content

Middleware and Implementation of extension method in ASP.Net Core

.Net .Net Core about 7 years ago || 2/11/2019 || 3.4 K View

  • Hide

Middleware is software that’s assembled on the application pipeline to handle request and responses over the pipeline.Middleware has access to both request and response. Middleware can process and pass the request to next middleware .Middleware can handle the request and short-circuit the pipeline. It can process outgoing response .Middleware is used to execute according to their own arrangement. Middleware can be of static page or dynamic so middleware mainly is used to call next middleware if required otherwise it sends response from its own side.

On startup.cs class there we can see two different methods configure and configure services from which we can configure Middleware as shown below:

 public void ConfigureServices(IServiceCollection services)
 {
      services.Configure<CookiePolicyOptions>(options =>
      {
           options.CheckConsentNeeded = context => true;
           options.MinimumSameSitePolicy = SameSiteMode.None;
       });


      services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
 }

 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
 {
      if (env.IsDevelopment())
        {
          app.UseDeveloperExceptionPage();
        }
      else
        {
           app.UseExceptionHandler("/Home/Error");
           app.UseHsts();
        }
        

      app.Use(async (Context,next) =>
        {
           await Context.Response.WriteAsync("hello i am first middleware!!!");
            await next();
        });
      app.Run(async (Context) =>
        {
           await Context.Response.WriteAsync("hello i am second middleware!");
        });

 }

Configure is the process that sets the request processing pipeline in asp.net core application as part of application startup .In case of configuring  middleware we need to focus on request delegates . Request delegates are used to build request pipeline. Request delegates are the delegates that take http context object as parameter as shown below:

 Delegates mainly use three different types of extension methods which are as follows

  • Run : it is implemented as an extension  method of an IApplicationbuilder interface of configure method as shown below :

                                                        

And this is the reason that here we are able to invoke the run method on the instances of IApplicationbuilder app. The parameter that we pass in the run method is the request delegate.Run extension method is considered as the terminal middleware .Terminal middleware is the middle ware that does not call next middleware or execute at the last step of request processing pipeline as shown in example below:

After running this program we will get following result as shown below      

So here after we add two different run extension method only first one is executed and second one is ignored or cannot get any response from second method so here we can say that run extension method is also called as terminal middleware. So here first method itself handles the request and responds to that request and the pipeline is reversed from there. So second middleware never gets the opportunity to execute and that’s the reason why we don’t see the message from second middleware in the browser. If we want the middleware to call the next middleware in the pipeline then we need to register our middleware using Use Extension method.

  • Use: Use Extension methods have two parameter in addition to http context object. It can also take a second parameter which is the next delegate .When we add next delegate it automatically calls the next piece of middleware in the pipeline. Here we add await keyword and invoke our next delegate

     

app.Use(async (Context,next) =>
            {
               await Context.Response.WriteAsync("hello i am first middleware!!!");
                await next();
            });
            app.Run(async (Context) =>
            {
                await Context.Response.WriteAsync("hello i am second middleware!");
            });

Now after we run this we get follwing result                  

 Notice we see the message from both middleware components

  • Map:  map extension method is used as the convention of branching pipeline. It branches the request pipeline based on the matches request pipeline path.
  • 1
  • 0
  • 0
    • Facebook
    • Twitter
    • Google +
    • LinkedIn

About author

Bibas Bhattarai

Bibas Bhattarai

Reset Your Password
Enter your email address that you used to register. We'll send you an email with your username and a link to reset your password.

Quick Survey