Understanding middleware in ASP.NET Core

Understanding middleware in ASP.NET Core

This article introduces ASP.NET Core Middleware concepts. By the end of this article, you will have a clear understanding of the following points.

What is Middleware?

Middleware (middleware or middleware) is a piece of code in the application pipeline used to process requests and responses.

For example, we can have a middleware component for user authentication, a middleware component for error handling, and another middleware component for serving static files such as JavaScript files, CSS files, various kinds of images, etc.

Middleware can be embedded as part of the .NET Core framework, added via NuGet packages, or written by the user. Middleware components are configured in the Configure method of the application startup class (Startup). The Configure method builds a request processing pipeline in an ASP.NET Core application. It consists of a series of request delegates called one after the other.

Typically, each middleware handles incoming requests and passes execution to the next middleware for further processing.

But the middleware component may also decide not to call the next piece of middleware in the pipeline. This is called short-circuiting, or request pipeline termination. Closing is often desirable because it avoids unnecessary work. For example, if it’s a request for a static file such as a CSS file, JavaScript, image, etc., the middleware for the static files can process and serve that request, and then close the rest of the pipeline.

Streamlining Middleware

Middleware components are executed in the order in which they are added to the pipeline, so be careful and add middleware in the correct order, otherwise the application may not work as you expect. The ordering of middleware is important for security, performance, and functionality.

The first middleware component in the configuration received the request, changed it (if necessary), and passed control to the next middleware. Likewise, the first middleware component is executed last when processing the response if we echo back. This is why exception handling delegates must be called very early in the pipeline so that they can inspect the result and display the eventual exception in a browser- and client-friendly way.

via ADO.NET

ASP.NET MVC – working with MySQL via ADO.NET

How should web APIs be tested

How should web APIs be tested?