Understanding ASP. NET 5 middleware and asp.net Middleware

Source: Internet
Author: User

Understanding ASP. NET 5 middleware and asp.net Middleware

This article, recommended today, describes how to implement and use ASP. NET 5 middleware.

Although in ASP. in NET 5, Microsoft did not emphasize OWIN (Open Web Interface. NET) and its official Microsoft OWIN implementation Katana, but some of the principles and design ideas are still ASP. NET 5 is carried in its own way. For example, decoupling the relationship between the server and the application, application delegation, and environment status can be found in ASP. NET 5 and enhanced.

So what is "Middleware? As defined in the OWIN specification, "middleware is a component that is passed in between the server and the application. It monitors, routes, or edits request and response messages for a specific purpose ." This definition is also applicable to ASP. NET 5, or can be considered as an HTTP module and processor in traditional ASP. NET. Some middleware completes some intermediate tasks, such as request verification, session state retrieval and persistence, logging, and so on. Some middleware finally generates a response message.

There is a very simple way to compile the middleware of ASP. NET 5. A Lambda expression can be done:

public class Startup{    public void Configure(IApplicationBuilder app)    {        app.Run(async context =>        {            context.Response.ContentType = "text/plain";            await context.Response.WriteAsync("Hello ASP.NET 5!");        });    }}

In the above Code, the delegate passed to the IApplicationBuilder. Run method is RequestDelegate, which is defined as follows:

public delegate Task RequestDelegate(HttpContext context);

RequestDelegate is equivalent to AppFunc in OWIN. The acceptance status information HttpContext is used as the input parameter and a Task is returned. Note that this HttpContext is not an HttpContext in SystemWeb, which is a context state object that encapsulates the request processing status and is transparent to the server (not specific to a server. The returned Task allows the caller to perform subsequent tasks only after your middleware completes the work. The Run method also has multiple overloading to allow you to inject dependencies.

RequestDelegate can also be used to concatenate the middleware into the execution pipeline:

public class Startup{    public void Configure(IApplicationBuilder app)    {        app.Use(next => async context =>        {            // do your stuff here before calling the next middleware             // in the pipeline                         await next.Invoke(context); // call the next guy             // do some more stuff here as the call is unwinding        });         app.Run(async context =>        {            context.Response.ContentType = "text/plain";            await context.Response.WriteAsync("Hello ASP.NET 5!");        });    }}

You can Use the IApplicationBuilder. Use method to concatenate your middleware code to the front of other middleware. The parameter "next" is the next middleware instance. The method is defined as follows:

IApplicationBuilder Use(Func<RequestDelegate, RequestDelegate

The above uses Lambda expressions to implement middleware, but the Code involved in actual development is complex, so it is best to put it into a separate class and provide the corresponding test code. In this way, you can compile, package, and distribute the middleware separately. Andrei Dzimchuk, author of this article, takes a simple middleware for HTTP Basic verification as an example to provide the following code:

public class BasicAuthentication{    private readonly RequestDelegate next;     public BasicAuthentication(RequestDelegate next)    {        this.next = next;    }     public async Task Invoke(HttpContext context,                              IAuthenticationService authenticationService)    {        try        {            var parser = new BasicAuthenticationParser(context);            var username = parser.GetUsername();            var password = parser.GetPassword();             await authenticationService.AuthenticateAsync(username, password);            await next(context);        }        catch (InvalidCredentialsException)        {            context.Response.StatusCode = 401;            context.Response.Headers.Add("WWW-Authenticate",                 new[] { "Basic" });        }    }}

This class is very interesting. First of all, it makes us very strange that it does not inherit any base class or implement any interfaces. From this we can see that Microsoft began to advocate the idea that "Conventions are better than Interfaces" in ASP. NET 5. We only need to implement a constructor that accepts RequestDelegate as the parameter, and an Invoke method with the same method signature as RequestDelegate. Of course, in this example, Invoke also accepts another parameter, which is the second strange thing. We can directly use dependency injection in the middleware. In this example, an IAuthenticationService is injected.

It is also very easy to use the written middleware. First, reference a dependency package "Microsoft. AspNet. RequestContainer", and then you can use the Microsoft. AspNet. Http. Extensions Extension Method IApplicationBuilder. UseMiddleware to load the middleware, as shown below:

builder.UseMiddleware<BasicAuthentication>();

Generally, we will write an extension class separately to provide a semantic extension method based on a specific extension method. The final Startup file can be written as follows:

public class Startup{    public void Configure(IApplicationBuilder app)    {        app.UseBasicAuthentication();         app.Run(async context =>        {            context.Response.ContentType = "text/plain";            await context.Response.WriteAsync("Hello ASP.NET 5!");        });    }}

At this point, we have completed the compilation and use of middleware. Of course, you also need to complete the registration of Code such as IAuthenticationService, which involves the dependency injection feature of ASP. NET 5 and has the opportunity to introduce it next time.

Original address in: http://dzimchuk.net/post/Understanding-ASPNET-5-middleware

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.