December 15, 2021

Requesting handler Web API in .NET 6

#requesting handler

#net6

#web api

#backend

Post Banner

The following post will cover routing, route handlers, route parameter for Web API in .NET 6

Routing

Supports both Map{Verb} and MapMethods

1 2 3 4 5 6 7 8 9 10 11 12 var builder = WebApplication.CreateBuilder(args); var app = builder.Build(); app.MapGet("/", () => "Routing using the GET"); app.MapPost("/", () => "Routing using the POST"); app.MapPut("/", () => "Routing using the PUT"); app.MapDelete("/", () => "Routing using the DELETE"); app.MapMethods("/options-or-head", new[] { "OPTIONS", "HEAD" }, () => "Routing using an options or head request"); app.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 2 3 4 5 6 // Inline lambda expression app.MapGet("/inline", () => "Hello Linh.Work"); // Variable lambda expression var handler = () => "Hello Linh.Work"; app.MapGet("/", handler);
Local function
1 2 3 4 5 6 7 8 9 // Local function using lambda string LocalFunction() => "Hello Linh.Work"; app.MapGet("/", LocalFunction); // Another local function string AnotherLocalFunction() =>{ return "Hello Linh.Work"; } app.MapGet("/", AnotherLocalFunction);
Class method
1 2 3 4 5 6 7 8 9 10 11 // Declare a class for given method static class ClassHandler { public static string Hello() { return "Hello Linh.Work"; } } // Using Instance method app.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:

1 2 app.MapGet("/hello/{name}", (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 !!!

Linh's Profile Image
Nguyen Chi Linh

I’m glad you’re here. I like the simple so I created this minimalist site to share what I’ve learned interesting during my journey in technologies and in life. Keep coding and enjoy exploring !!!

Buy me a coffee