What is Asp.Net Core Middleware? How to Use Middleware in Web Application?

Introduction to Asp.Net Core Middleware:

In Simple terms, if we say what is Middleware then it’s nothing but a bridge between Database and application. Let’s say, that Asp.Net Core Middleware is also a bridge provider between two components. Middleware determines How to respond to HTTP requests in Asp.Net Core.

So let’s say Middleware is a software component that is assembled into an application to handle requests and responses to perform some actions before or after the next component Invoke.

Suppose in our application we need to handle an error in a different way when we are in development mode then we handle the error using “UseDeveloperExceptionPage()” otherwise we will redirect to an error page using “UseExceptionHandler()”. And if we don’t get any type of errors then middleware directly calls the next component.

How to Use Asp.Net Core Middleware?


using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;

namespace MyFirstCoreApplication
{
	public class Startup
	{
		public Startup(IConfiguration configuration)
		{
			Configuration = configuration;
		}

		public IConfiguration Configuration { get; }

		// This method gets called by the runtime.
		// Use this method to add services to the container.
		public void ConfigureServices(IServiceCollection services)
		{
			// Add services to the container if needed.
		}

		// This method gets called by the runtime.
		// Use this method to configure the HTTP request pipeline.
		public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
		{
			if (env.IsDevelopment())
			{
				app.UseDeveloperExceptionPage();
			}
			else
			{
				app.UseExceptionHandler("/Home/Error");
				app.UseHsts();
			}

			app.UseHttpsRedirection();
			app.UseStaticFiles();

			app.UseRouting();

			app.UseAuthorization();

			app.UseEndpoints(endpoints =>
			{
				endpoints.MapGet("/", async context =>
				{
					var msg = Configuration["message"];
					await context.Response.WriteAsync(msg);
				});
			});
		}

		// Entry point for the application.
		public static void Main(string[] args)
		{
			CreateHostBuilder(args).Build().Run();
		}

		public static IHostBuilder CreateHostBuilder(string[] args) =>
			Host.CreateDefaultBuilder(args)
				.ConfigureWebHostDefaults(webBuilder =>
				{
					webBuilder.UseStartup();
				});
	}
}

Let’s say in the above code there is one Configure Method, we will add our middleware inside this method using the IApplicationBuilder interface.

In the above code, you saw that Inside the Configure method, there are two middleware already present in our empty project.

  1. app.UseIISPlatformHandler();
  2. app.run();
    • IISPlatformHandler: Basically IISPlatformHandler allows to work with Windows identity, and It will check every incoming request and see whether any Windows identity information is associated with every request or not, and based on that information it will call the next middleware.
    • App.run: Basically app.run middleware is used to register middleware and the run method will pass to another method, and we can use it to process every single response.

Also Read: What is ASP.NET Core? Advantage(Pros) of ASP.NET Core Technology

How to Add Middleware to Our Application?

Now, we will see how to add middleware to our application using NuGet Packages.

  1. Right-click on the project and select Manage NuGet packages.
    middleware
  2. In the Manage Nuget Package console search for Microsoft.aspnetCore.diagnostics and Click on Install will Install library of Exception Handling In our project.
    middleware
  3. Now click on Startup.cs file which is on the root of our application.And find the Configure method and Write this piece of code inside the Configure method to add asp.net core middleware in our application.if (env.IsDevelopment()){
    app.UseDeveloperExceptionPage();
    }
    middleware

Keep with us for more tips and tricks about the ASP.NET Core Development and Middleware concepts.

I hope you would like my blog to help the awareness about middleware and how to use middleware concepts in real-time websites and web apps. You can share this blog via a social button to help other Asp.Net Developers.

Article by

Chintan Prajapati

Chintan Prajapati, a seasoned computer engineer with over 20 years in the software industry, is the Founder and CEO of Satva Solutions. His expertise lies in Accounting & ERP Integrations, RPA, and developing technology solutions around leading ERP and accounting software, focusing on using Responsible AI and ML in fintech solutions. Chintan holds a BE in Computer Engineering and is a Microsoft Certified Professional, Microsoft Certified Technology Specialist, Certified Azure Solution Developer, Certified Intuit Developer, and Xero Developer.Throughout his career, Chintan has significantly impacted the accounting industry by consulting and delivering integrations and automation solutions that have saved thousands of man-hours. He aims to provide readers with insightful, practical advice on leveraging technology for business efficiency.Outside of his professional work, Chintan enjoys trekking and bird-watching. Guided by the philosophy, "Deliver the highest value to clients". Chintan continues to drive innovation and excellence in digital transformation strategies from his base in Ahmedabad, India.