...

/

Middleware with Anonymous Inline Delegate & Decompression Support

Middleware with Anonymous Inline Delegate & Decompression Support

Learn about implementing an anonymous inline delegate, handling specific routes, and outputting relevant information about chosen endpoints.

Implementing an anonymous inline delegate as middleware

A delegate can be specified as an inline anonymous method. We will register one that plugs into the pipeline after routing decisions for endpoints have been made. It will output which endpoint was chosen, as well as handling one specific route: /bonjour. If that route is matched, it will respond with plain text without calling any further into the pipeline to find a match:

Step 1: In the Northwind.Web project, in Program.cs, add statements before the call to UseHttpsRedirection to use an anonymous method as a middleware delegate, as shown in the following code:

Press + to interact
app.Use(async (HttpContext context, Func<Task> next) =>
{
RouteEndpoint? rep = context.GetEndpoint() as RouteEndpoint;
if (rep is not null)
{
WriteLine($"Endpoint name: {rep.DisplayName}");
WriteLine($"Endpoint route pattern: {rep.RoutePattern.RawText}");
}
if (context.Request.Path == "/bonjour")
{
// in the case of a match on URL path, this becomes a terminating
// delegate that returns so does not call the next delegate
await context.Response.WriteAsync("Bonjour Monde!");
return;
}
// we could modify the request before calling the next delegate
await next();
// we could modify the response after calling the next delegate
});

Step 2: Start the website.

Step 3: In the browser, navigate to https://localhost:5001, look at the console output and note a match on an endpoint route /; it was processed as /index, and the Index.cshtml Razor Page was executed to return the response, as shown in the following output:

Endpoint name: /index
Endpoint route pattern:

Step ...