December 15, 2021
Requesting handler Web API in .NET 6

The following post will cover routing, route handlers, route parameter for Web API in .NET 6
Routing
Supports both Map{Verb} and MapMethods
1var builder = WebApplication.CreateBuilder(args); 2var app = builder.Build(); 3 4app.MapGet("/", () => "Routing using the GET"); 5app.MapPost("/", () => "Routing using the POST"); 6app.MapPut("/", () => "Routing using the PUT"); 7app.MapDelete("/", () => "Routing using the DELETE"); 8 9app.MapMethods("/options-or-head", new[] { "OPTIONS", "HEAD" }, 10 () => "Routing using an options or head request"); 11 12app.Run();
Route Handlers
Route handlers let you define methods that execute when the route matches. It can be a lambda expression, a local function, an class method.
Lambda expression
1// Inline lambda expression 2app.MapGet("/inline", () => "Hello Linh.Work"); 3 4// Variable lambda expression 5var handler = () => "Hello Linh.Work"; 6app.MapGet("/", handler);
Local function
1// Local function using lambda 2string LocalFunction() => "Hello Linh.Work"; 3app.MapGet("/", LocalFunction); 4 5// Another local function 6string AnotherLocalFunction() =>{ 7 return "Hello Linh.Work"; 8} 9app.MapGet("/", AnotherLocalFunction);
Class method
1// Declare a class for given method 2static class ClassHandler 3{ 4 public static string Hello() 5 { 6 return "Hello Linh.Work"; 7 } 8} 9 10// Using Instance method 11app.MapGet("/", ClassHandler.Hello);
Route Parameters
Route parameters are named URL segments that are used to capture the values specified at their position in the URL.
For example:
1app.MapGet("/hello/{name}", 2 (string name) => $"Hello I'm {userId}");
The result will return Hello I'm Linh.Work if the url /hello/Linh.Work
That's it for now. Keep coding and enjoy exploring !!!