Use of Middleware in ASP.NET Core 3.1 - Lesson 1

Use of Middleware in ASP.NET Core 3.1 - Lesson 1


Middleware is a piece of software that can handle an HTTP request or response.


For example, you can use middleware;


- to authenticate a user
- to handle errors
- to serve static files such as JavaScript files, CSS files, images etc.


Users can make a request from the website. In response to this request, appropriate responses are generated and sent by the server.


Middleware is the pipeline for handling web requests in ASP.NET Core.


A piece of middleware sends a response to the client (short-circuit) or it may call the next piece of middleware in the pipeline.
The piece of middleware gives you a reference to the next piece of middleware in the pipeline


It's important to be aware that a middleware component does not have to call the next middleware component in all cases.
For example, you may have some middleware checking for an API key. If the key is not available, then you may want to write a response directly and short-circuit the rest of the pipeline.
After all, there is probably not a need to execute your secure controller actions if the user is unauthenticated


middleware.png

Middleware is configured in the Configure method in the Startup.cs file.


- Create a Web API project named Middleware using Visual Studio


- Add a class named CustomMiddleware


using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;

namespace Middleware
{
    public class CustomMiddleware
    {
        private readonly RequestDelegate _next;
        public CustomMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext httpContext)
        {
            //Basic Authentication
            var auth = httpContext.Request.Headers.Keys.Contains("Authorization");
            if(!auth)
            {
                httpContext.Response.StatusCode = 400;
                await httpContext.Response.WriteAsync("Invalid Request");
            }

            await _next.Invoke(httpContext);
        }
    }
}

Middleware is registered in the Configure method of Startup.cs.
The Configure method has an IApplicationBuilder argument that provides the methods necessary for middleware registration.


To register middleware, the standard way is with UseMiddleware


public void Configure(IApplicationBuilder  app)
{
	app.UseMiddleware();
}

You rarely need to call UseMiddleware directly. The standard approach is to write extension methods.
The extension method registers the middleware with UseMiddleware.


- Add a class named MiddlewareExtension


using Microsoft.AspNetCore.Builder;

namespace Middleware
{
	public static class MiddlewareExtension
	{
		public static IApplicationBuilder UseCustomMiddleware(this IApplicationBuilder app)
		{
			app.UseMiddleware();
			return app;
		}
	}
}

As the last step, let's activate middleware in the Configure method.


public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
	app.UseCustomMiddleware();

	...
}

- Start the project. When you make a call to any end point in your project using postman or any browser as below, if you don't send the expected parameter in the header, you will receive an error.


middleware1.png

middleware2.png

Using Postman, if we send the Authorization header correctly, we can reach endpoint without any problem as shown below. So that we get a success response with HTTP Status 200 OK


middleware3.png

Download the source code.