Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
.NET Core Web Application - Inline middleware to test how endpoint information can be accessed
// Startup.cs
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// Before UseRouting
app.Use(next => context =>
{
Console.WriteLine($"1. Endpoint: {context.GetEndpoint()?.DisplayName ?? "Not Set"}");
return next(context);
});
app.UseRouting();
// After UseRouting
app.Use(next => context =>
{
Console.WriteLine($"2. Endpoint: {context.GetEndpoint()?.DisplayName ?? "Not Set"}");
return next(context);
});
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async (context) =>
{
Console.WriteLine($"3. Endpoint: {context.GetEndpoint()?.DisplayName ?? "Not Set"}");
await context.Response.WriteAsync($"Hello World");
}).WithDisplayName("Default Endpoint");
endpoints.MapGet("/{name}", async (context) =>
{
Console.WriteLine($"3. Endpoint: {context.GetEndpoint()?.DisplayName ?? "Not Set"}");
var name = context.Request.RouteValues["name"];
await context.Response.WriteAsync($"Hello {name}");
}).WithDisplayName("Name Endpoint");
});
// After UseEndpoints
// Executed only if there is no matching endpoint
app.Use(next => context =>
{
Console.WriteLine($"4. Endpoint: {context.GetEndpoint()?.DisplayName ?? "Not Set"}");
return next(context);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment