Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

How to Use ASP.NET Middleware in Web Apps

DZone's Guide to

How to Use ASP.NET Middleware in Web Apps

In this article, you'll learn how to use middle ware to respond to HTTP requests, rather than HTTP Modules, using ASP.NET Core.

· Web Dev Zone
Free Resource

Add user login and MFA to your next project in minutes. Create a free Okta developer account, drop in one of our SDKs to your application and get back to building.

Middleware is quite simply a bridge between database and application. In the context of ASP.NET Core, middleware is also a bridge between two components. It is middleware that decides how to respond to HTTP requests in ASP.NET Core. ASP.NET app experts are often looking at Middleware to handle requests or to be a bridge.

Middleware also controls how the application looks when there is an error, and it is a key link in authenticating and authorizing users to perform specific actions. In other words, middleware are software components assembled into an application to handle request and response to performing user actions before/after another component is invoked.

Request delegates are used to build the request pipeline. The request delegates take care of each HTTP request.

But let’s say the error in the application needs to be handled in a different way. If we are in the development mode then this can be done using “UseDeveloperExceptionPage()” otherwise the error page can be directed using “UseExceptionHandler()”.

Image title

How to Use Asp.Net Core Middleware?

using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
namespace MyFirstCoreApplication
{
public class Startup
{
public Startup()
{
var builder = new ConfigurationBuilder()
.AddJsonFile(“AppSettings.json”);
Configuration = builder.Build();
}
public IConfiguration Configuration { get; set; }
// This method gets called by the runtime.
// Use this method to add services to the container.
// For more information on how to configure your application,
// visit http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
}
// This method gets called by the runtime.
// Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app)
{
app.UseIISPlatformHandler();
app.Run(async (context) => {
var msg = Configuration[“message”];
await context.Response.WriteAsync(msg);
});
}
// Entry point for the application.
public static void Main(string[] args) => WebApplication.Run(args);
}
}

For example’s sake, we may assume that in the above code, there is one Configure Method. We will add our middleware inside this method using the IApplicationBuilder interface.

The above code demonstrates that the Inside Configure method already has two middleware present in our empty project.

app.UseIISPlatformHandler();  and app.run(); 

  • IISPlatformHandler: Basically IISPlatformHandler allows working with Windows identity and checks every incoming request to see whether any identity information is associated with every request or not. It will invoke the next middleware based on that information.

  • App.run: On the other hand, middleware defined using app.Run will never call subsequent middleware and the run method will pass on to another method. The Run method short-circuits the pipeline (that is, it does not call a next request delegate). Run is a convention, and some middleware components may expose Run[Middleware] methods that run at the end of the pipeline.

How to Add Middleware in Our Application?

Let’s see how to add to add middleware in our application using NuGet Packages.

Step 1: Right click on project and choose Manage NuGet packages.

Image title

Step 2: In the Manage NuGet Package console, find Microsoft.aspnetCore.diagnostics and select Install to Install the library for Exception Handling in our project.

Image title

Step 3: Next you click on the Startup.cs file which is in the root of our application.

And find the Configure method and write this piece of code inside Configure method to add ASP.NET Core middleware in our application:

if (env.IsDevelopment()){
app.UseDeveloperExceptionPage();
}

Image title

Finally

As you can see, middleware is like the new ‘pipeline’ for requests in ASP.NET Core. Each piece can process part or all of the request. Anywhere you would normally write an HTTP Module in the full ASP.NET Framework is where you should probably now be using middleware. However, please note that app middleware is constructed at start-up. If you require scoped dependencies or anything other than singletons, do not inject your dependencies. 

Launch your application faster with Okta’s user management API. Register today for the free forever developer edition!

Topics:
asp.net ,web apps ,web dev ,middleware

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}