Home  >  Article  >  Backend Development  >  How to set up middleware in asp.net core example tutorial

How to set up middleware in asp.net core example tutorial

零下一度
零下一度Original
2017-06-16 10:04:231685browse

Asp.Net Core-Middleware

In this chapter, we will learn how to set up middleware. Middleware technology in ASP.NET Core controls how our applications respond to HTTP requests. It can also control application exception errors, which is a key in how users are authenticated and authorized to perform specific actions.

  • Middleware is a software component assembled into an application's pipeline to handle requests and responses.

  • Each component can choose whether to pass the request to the next component in the pipeline, and can perform certain actions before and after tasks in the pipeline.

  • The Request delegate is used to build the request pipeline. The Request delegate is used to handle each HTTP request.

  • Every piece of middleware in ASP.NET Core is an object, and each piece has a very specific, focused and limited role.

  • Ultimately, we need a lot of middleware to provide appropriate behavior for the application.

Now let’s assume we want to log every request to our application.

  • In this case, the first piece of middleware we install into the application is a logging component.

  • This logger can see all incoming requests, and then the middleware just logs some information, and then passes the request to the next block of middleware.

  • Middleware appears in this processing pipeline as a series of components.

  • The next middleware we install into our application is an authorization component.

  • A component might be looking for a specific cookie or accessing a token in the HTTP header.

  • If the authorization component finds a token, it allows the request to continue.

  • If not, the authorization component itself may respond to the request with an HTTP error code or redirect the user to the login page.

  • Otherwise, the authorization component passes the request to the next router's middleware.

  • A router looks at the URL and determines the next action.

  • The router is making some responses. If the router does not find any response, the router itself may return a 404 Not Found error.


Case

Now let us understand more about middleware through a simple example. We configure the middleware component by using the Configure method of our startup class.


using Microsoft.AspNet.Builder; 
using Microsoft.AspNet.Hosting; 
using Microsoft.AspNet.Http; 
using Microsoft.Extensions.DependencyInjection; 
using Microsoft.Extensions.Configuration;  
namespace FirstAppDemo { 
   public class Startup { 
      public Startup() { 
         var builder = new ConfigurationBuilder() 
            .AddJsonFile("AppSettings.json"); 
         Configuration = builder.Build(); 
      }  
      public IConfiguration Configuration { get; set; }  
        
      // This method gets called by the runtime. 
      // Use this method to add services to the container. 
      // For more information on how to configure your application, 
      // visit http://go.microsoft.com/fwlink/?LinkID=398940 
      public void ConfigureServices(IServiceCollection services) { 
      }  
       
      // This method gets called by the runtime.  
      // Use this method to configure the HTTP request pipeline. 
      public void Configure(IApplicationBuilder app) { 
         app.UseIISPlatformHandler();  
          
         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); 
   } 
}
Configure()方法内,我们将调用IApplicationBuilder接口的扩展方法来添加中间件。

By default in a new empty project there are two pieces of middleware -

  • IISPlatformHandler

  • Middleware registered with app.Run


IISPlatformHandler

IISPlatformHandler allows us to use Windows Authentication. It will look at each incoming request to see if there are any Windows identity related requests and then call the next block middleware.

Middleware registered with app.Run

In this case a middleware is registered with app.Run. The Run method allows us to pass in another method that we can use to handle each response. The Run method is not something you often see, we can call it a middleware terminal.

The middleware you register to run will never have the opportunity to call another middleware. The only thing it can do is receive the request and produce some kind of response.

You also have access to a response object, and you can add some strings to the response object.

If you want to register another middleware after app.Run, this middleware will never be called, because the Run method is the terminal of a middleware. It doesn't call the next block middleware.

How to add a middleware

Let us proceed with the following steps to add another middleware −

Step 1−Right click on the project and select Manage NuGet Packages.

Step 2− Search for Microsoft.aspnet.diagnostics, this particular package contains many different kinds of middleware that we can use.

Step 3−If the package is not installed in your project, then choose to install the package.

Step 4−Now let us call the app.UseWelcomePage middleware in the Configure() method.


// This method gets called by the runtime.  
// Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app) { 
   app.UseIISPlatformHandler(); 
   app.UseWelcomePage();  
    
   app.Run(async (context) => { 
      var msg = Configuration["message"]; 
      await context.Response.WriteAsync(msg); 
   });

Step 5 − Run your application and you will see the following welcome screen.

This welcome screen may not be that useful.

Step 6− Let’s try something else that might be more useful, instead of using the welcome page, we will use the RuntimeInfoPage.


 1 // This method gets called by the runtime.  
 2 // Use this method to configure the HTTP request pipeline.  3 public void Configure(IApplicationBuilder app) { 
 4    app.UseIISPlatformHandler(); 
 5    app.UseRuntimeInfoPage();  
 6      7    app.Run(async (context) => { 
 8       var msg = Configuration["message"]; 
 9       await context.Response.WriteAsync(msg); 
10    });  
11 }

Step 7 − Save your Startup.cs page and refresh your browser, you will see the page below.

This RuntimeInfoPage is middleware that will only respond to requests for a specific URL. If the incoming request does not match the URL, this middleware simply passes the request on to the next piece of middleware. The request will go through the IISPlatformHandler middleware and then go to the UseRuntimeInfoPage middleware. It doesn't create a response, so it goes to our application. Run and display the string.

Step 8−We add “runtimeinfo” at the end of the URL. You will now see a page that is runtime information page by the middleware.

You will see a return page, which shows you some information about your runtime environment, such as operating system, runtime version, structure, type and the type you are running. Information about all packages used.

The above is the detailed content of How to set up middleware in asp.net core example tutorial. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn