Working with middleware

Middleware are part of the ASP.NET Core 3 request pipeline for handling requests and responses. When they are chained together, they can pass incoming requests from one to another and perform actions before and after the next middleware is called within the pipeline:

Using middleware allows your applications to be more flexible and evolutive since you can add and remove middleware easily in the Configure method of the Startup class.

Furthermore, the order in which you call the middleware in the Configure method is the order in which they are going to get invoked. It is advisable to call middleware in the following order so as to ensure better performance, functionality, and security:

  1. Exception handling middleware
  2. Static files middleware
  3. Authentication middleware
  4. MVC Middleware

If you do not call them in this order, you might get some unexpected behavior and even errors, since middleware actions might be applied too late or too early within the request pipeline.

For example, if you do not call the exception handling middleware first, you might not catch all of the exceptions that occur before its invocation. Another example is when you call the response compression middleware after the static files middleware. In this case, your static files will not be compressed, which might not be the desired behavior. So, take care of the ordering of your middleware calls; it can make a huge difference.

The following are some of the built-in middleware you can use in your applications (the list is not exhaustive; there are many more):

Authentication

OAuth 2 and OpenID authentication, based on the newest version of IdentityModel

CORS

Cross-origin resource sharing protection, based on HTTP headers

Response caching

HTTP response caching

Response compression

HTTP response gzip compression

Routing

HTTP request routing framework

Session

Basic local and distributed session object management

Static files

HTML, CSS, JavaScript, and image support including directory browsing

URL rewriting

URL SEO optimization and rewriting

 

The built-in middleware will be sufficient for the most basic requirements and standard use cases, but you will surely need to create your own middleware. There are two ways of doing that: creating them inline in the Startup class or creating them within a self-contained class.

Let's look at how to define inline middleware first. Here are the methods available:

  • Run
  • Map
  • MapWhen
  • Use

The Run method is used to add middleware and immediately return a response, thus short-circuiting the request pipeline. It does not call any of the following middleware and ends the request pipeline. It is therefore advisable to place it at the end of your middleware calls (refer to middleware ordering, discussed previously).

The Map method allows a certain branch to be executed and the corresponding middleware to be added if the request path starts with a specific path, which means you can effectively branch the request pipeline.

The MapWhen method provides basically the same concept of branching the request pipeline and adding a specific middleware, but with control over the branching conditions, since it is based on the result of a Func<HttpContext, bool> predicate.

The Use method adds middleware and either allows the next middleware to be called in line or the request pipeline to be short-circuited. However, if you want to pass on the request after executing a specific action, you have to call the next middleware manually by using next.Invoke with the current context as a parameter.

Here are some examples of how to use these extension methods, first with ApiPipeline and WebPipeline:

     private static void ApiPipeline(IApplicationBuilder app)  { 
      app.Run(async context => 
      { 
        await context.Response.WriteAsync("Branched to Api 
Pipeline."); }); } private static void WebPipeline(IApplicationBuilder app) { app.MapWhen(context => { return context.Request.Query.ContainsKey("usr"); }, UserPipeline); app.Run(async context => { await context.Response.WriteAsync("Branched to Web
Pipeline."); }); }

Then, there is UserPipeline and the Configure method, which makes use of the pipelines created:

  
 
     private static void UserPipeline(IApplicationBuilder app)     { 
      app.Run(async context => 
      { 
        await context.Response.WriteAsync("Branched to User 
Pipeline."); }); } public void Configure(IApplicationBuilder app,
IHostingEnvironmentenv) { app.Map("/api", ApiPipeline); app.Map("/web", WebPipeline); app.Use(next =>async context => { await context.Response.WriteAsync("Called Use."); await next.Invoke(context); }); app.Run(async context => { await context.Response.WriteAsync("Finished with Run."); }); }

As shown before, you can create your middleware inline, but this is not recommended for more advanced scenarios. We advise you to put your middleware in self-contained classes in this case, and the process for doing so is really easy. Middleware is just a class with a certain structure that is exposed via an extension method.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.138.104