ASP.NET Core Middleware and Create Custom Middleware:

This article discusses definition of middleware in ASP.NET Core and how they can be used in ASP.NET Core 2.0

In ASP.NET Core middleware are C# classes that can handle an HTTP request and response. Middleware can either:

  1. Handle a incoming HTTP request by generating an HTTP response.
  2. Process an incoming HTTP request, modify it, and pass it on to another piece of middleware.
  3. Process an outgoing HTTP response, modify it, and pass it on to either another piece of middleware or ASP.NET Core web server.

The most important piece of middleware in most ASP.NET Core applications is the Middleware. This normally generates your HTML pages and API responses – In other words it typically receives a request, generates a response, and then sends it back to the user.

Middleware pipeline is configured in the Startup.cs‘s appropriately  named Configure method.

Here’s an example of a simple pipeline that uses MVC:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler(“/Home/Error”);
}

app.UseStaticFiles();

app.UseMvc(routes =>
{
routes.MapRoute(
name: “default”,
template: “{controller=Home}/{action=Index}/{id?}”);
});
}

The DeveloperExceptionPage, StaticFiles and MVC are all middleware and they run in the order defined.

Developer ExceptionPage middleware handles exceptions raised in the middlewares below of it.

Steps to Create Custom Middleware:

Step1 : Create an Interface with name ICustomer

public interface ICustomer
{
string GetWelcomeMessage();
}

Step2 : Create an Implementation class for this Interface with name Customer

public class Customer : ICustomer
{
string ICustomer.GetWelcomeMessage()
{
return “Welcome back…!!”;
}
}

Step 3: In Startup.cs file , you need to register service “ICustomer” with implementation class also define scope as mentioned below:

public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<ICustomer, Customer>();
}

Below method will invoke on every HTTP request and it will call method on customer interface which was registered with implementation class “Customer” in above step…

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ICustomer customer)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

app.Run(async (context) =>
{
var welcomemessage = customer.GetWelcomeMessage();
await context.Response.WriteAsync(welcomemessage + “My Service Injection”);
});
}

Output: Run application to see output result on browser.