Saturday, 7 August 2021

Middleware in dot net core

 What is Middleware?

 

Middleware is a piece of code in an application pipeline used to handle requests and responses.

 

For example, we may have a middleware component to authenticate a user, another piece of middleware to handle errors, and another middleware to serve static files such as JavaScript files, CSS files, images, etc.

 

Middleware can be built-in as part of the .NET Core framework, added via NuGet packages, or can be custom middleware. These middleware components are configured as part of the application startup class in the configure method. Configure methods set up a request processing pipeline for an ASP.NET Core application. It consists of a sequence of request delegates called one after the other.


public void Configure(IApplicationBuilder app, IWebHostEnvironment env)    

{    

    if (env.IsDevelopment())    

    {    

        //This middleware is used reports app runtime errors in development environment.  

        app.UseDeveloperExceptionPage();    

    }    

    else    

    {    

        //This middleware is catches exceptions thrown in production environment.   

        app.UseExceptionHandler("/Error");   

        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.    

        app.UseHsts(); //adds the Strict-Transport-Security header.    

    }    

    //This middleware is used to redirects HTTP requests to HTTPS.  

    app.UseHttpsRedirection();   

    

    //This middleware is used to returns static files and short-circuits further request processing.   

    app.UseStaticFiles();  

    

    //This middleware is used to route requests.   

    app.UseRouting();   

    

    //This middleware is used to authorizes a user to access secure resources.  

    app.UseAuthorization();    

    

    //This middleware is used to add Razor Pages endpoints to the request pipeline.    

    app.UseEndpoints(endpoints =>    

    {    

        endpoints.MapRazorPages();               

    });    

No comments:

Post a Comment