Last active
May 26, 2021 20:17
-
-
Save manoj-choudhari-git/cee43c94c6b6491f64dd33e4a26d05c0 to your computer and use it in GitHub Desktop.
.NET Core Web Application - Inline middleware to test how endpoint information can be accessed
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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