[ASP.NET Core MVC Pipeline] Middleware Pipeline

The ASP.NET Core MVC Pipeline
The ASP.NET Core MVC Pipeline
Middleware Pipeline
Middleware Pipeline

What is a Middleware?

Middleware Pipeline
Middleware Pipeline
  • A middleware can execute successfully its function and still pass the request to next middleware, therefore allowing for more changes before sending the response.
  • The routing middleware is certainly an important one but he is not vital on the middleware pipeline. It is vital to the MVC Framework, but you could have a perfectly working application without the routing middleware.

Our first Middleware

public class Startup
{
// ... More Code

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseDeveloperExceptionPage(); // Exception Handling Page Middleware

app.UseStaticFiles(); // Static Files serving Middleware

app.UseMvcWithDefaultRoute(); // MVC Routing Middleware
}
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseDeveloperExceptionPage(); // Exception Handling Page Middleware

app.UseStaticFiles(); // Static Files serving Middleware

/* Custom Middleware Inline */
app.Use(async (context, next) =>
{
if (context.Request.Method == "GET")
await next();
else
await context.Response.WriteAsync("Invalid method");
});
/* End Custom Middleware Inline */

app.UseMvcWithDefaultRoute(); // MVC Routing Middleware
}

Order Matters

Before AND After the next Middleware

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseStaticFiles();

app.Use(async (context, next) =>
{
// Execute some BEFORE before calling the next middleware
await next();
// Execute some AFTER before calling the next middleware
});

app.UseMvcWithDefaultRoute();
}

Use, Run or Map

app.Use(async (context, next) => { 
// Our custom logic
if(something)
{
await next();
// More custom logic
}
else
{
// Next middleware is never called on this path
}
});
app.Map("/CustomPath", (appPath1) =>
{
appPath1.Use(async (context, next) =>
{
// Cuustom Middleware code for Path 1
await next();
});
});

app.Map("/AnotherCustomPath", (appPath2) =>
{
appPath2.Run(async (context) =>
{
// Custom Middleware code for Path 2
await context.Response.WriteAsync("Done");
});
});
app.MapWhen(context => context.Request.IsHttps, appContext =>
{
appContext.Use(async (context, next) =>
{
// Custom Logic
await next();
});
});

app.MapWhen(context => context.Request.Method == "GET", appContext =>
{
appContext.Run(async context =>
{
await context.Response.WriteAsync("Done!");
});
});

Creating our Custom Middleware

public class CustomHeadersMiddleware
{
private readonly RequestDelegate next;

public CustomHeadersMiddleware(RequestDelegate next)
{
this.next = next;
}

public Task Invoke(HttpContext context)
{
return next(context);
}
}
  • The Middleware must have a Constructor that accepts one RequestDelegate
  • The Middleware must have a public Method that receives an HttpContext as parameter and returns a Task type.
public class CustomHeadersMiddleware
{
private readonly RequestDelegate next;

public CustomHeadersMiddleware(RequestDelegate next)
{
this.next = next;
}

public async Task Invoke(HttpContext context)
{
if (context.Request.Method == "GET")
{
context.Response.Headers.Add("AzureCoderBlog", DateTime.UtcNow.ToString());
await next(context);
}
else
{
await context.Response.WriteAsync("Method not Allowed");
}
}
}

Hookup with the Middleware Pipeline!

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseStaticFiles();

app.UseMiddleware<CustomHeadersMiddleware>();

app.UseMvcWithDefaultRoute();
}
public static class CustomHeadersMiddlewareExtensions
{
public static IApplicationBuilder UseCustomHeaders(this IApplicationBuilder app)
{
return app.UseMiddleware<CustomHeadersMiddleware>();
}
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseStaticFiles();

app.UseCustomHeaders();

app.UseMvcWithDefaultRoute();
}
Middleware Samples
Middleware Samples

--

--

--

Software Development and everything that encircles it :)

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

(C++) Math Practice

GO-SQUAD 3.0 : First Week Post-Bootcamp

Windows application Test Automation (Part 1)

IS “AGILE” THE FUTURE OF WORK?

Atom Text Editor

The nil value in Ruby

Getting started with KubeEdge on virtual machines

My Journey to Kubernetes onto Bare Metal — Part 4: MetalLB

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Lucas Araujo | Azure Coder

Lucas Araujo | Azure Coder

Software Development and everything that encircles it :)

More from Medium

Access ORACLE (OCI) mysql instance from public internet

Deploy Flask app on Azure in 3 steps

Angular 11 + Firebase Cloud Messaging Push Notifications — Devstringx

Sharp Notes to SQL Users Migrating to DynamoDB