ASP.NET Core

Built-in Middleware in ASP.NET Core

Built-in Middleware in ASP.NET Core

Built-in Middleware in ASP.NET Core

There are large number of Built-in Middleware in ASP.NET Core, we can use only the ones which we need in our app. Built-in Middleware do following important tasks Authorization, Authentication, Diagnostics, Error handling and logging, Routing etc


Routing Middleware:
Use Routing middleware to assign requests to respective resources. For EG, assign a particular action of a controller for showing the employees data for a given day.
Asp.Net Core already instructed the app to use routing by the code line app.UseRouting().
Lets create a default route in the program class to show employees data.

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");




Diagnostic Handling Middleware:
1. Lets Install our NuGet Package 'Microsoft.aspnetcore.diagnostics' - that is actually ASP.NET Core middleware for exception handling. This package contains many different pieces of middleware that we can use
2. Register Middleware in Startup/Program Class
    Inside Configure() method - invoke the extension methods on the IApplicationBuilder interface to register our middleware.
   Registered Middleware with app.Run - The Run method allows us to pass in another method, which we can use to process every single response.
   A. IISPlatformHandler middleware:
       Allows us to work with Windows authentication. It will look at every incoming request and see if there is any Windows
       identity information associated with that request and then it calls the next piece of middleware.. 
      Middleware that you register with Run will never have the opportunity to call another piece of  middleware, all it does is receive a request, and then it has to produce some sort of response
  B. The RuntimeInfoPage middleware:
      only respond to requests that come in for a specific URL. If the incoming request does not match that URL,
      this piece of middleware just lets the request pass through to the next piece of middleware..
      The request will pass through the IISPlatformHandler middleware, then go to the UseRuntimeInfoPage middleware.


// Register in Asp.net Core 3.1 in startup file
public void Configure(IApplicationBuilder app) {
    app.UseIISPlatformHandler();  
    app.UseRuntimeInfoPage();

    app.Run(async (context) => {
    var msg = Configuration["message"];
    await context.Response.WriteAsync(msg);
    });  
}  
// Entry point for the application.
public static void Main(string[] args) => WebApplication.Run<Startup>(args);

3: Run the application, in address bar add “/runtimeinfo” at the end of your URL. You will now see a page that is produced by that runtime info page middleware.



Exception Handling Middleware
In an Empty Template, we can add the Exceptional Handling Middleware to get detailed message about error coming in the application.

To handle Exceptions and show the proper  message to end user: -
1. Enable Exception Handling.
2. Additionally, we can add ExceptionHandler Middleware in the program class
   app.UseDeveloperExceptionPage();
3. Enable StatusCodePages to handle responses with status codes between 400 and 599
   app.UseStatusCodePages();
4. Now re-run your application and re-visit the URL – https://localhost:44343/middleware1
(this controller and action actually not exists in our application)


The first line shows due to our UseStatusCodePages middleware
The second line shows due to our custom
ResponseEditingMiddleware middleware


We can intentionally throw an exception in case of any error by adding

public IActionResult Exception()
{
    throw new System.NullReferenceException();
}

Now we will see full Exception message with Stack Trace to explore the cause of the exception.



Register Middleware Using Extention Method
We
Register Middleware Using Extension method







Related Post

About Us

Community of IT Professionals

A Complete IT knowledgebase for any kind of Software Language, Development, Programming, Coding, Designing, Networking, Hardware and Digital Marketing.

Instagram