Map extension methods in Asp.net Core

Map extension methods in Asp.net Core
ASP.NET Core provides a family of Map* extension methods on the IEndpointRouteBuilder interface that simplify endpoint creation:
MapGet: Creates an endpoint that only handles GET requests.
MapPost: Creates an endpoint that only handles POST requests.
MapPut, MapDelete: Create endpoints for PUT and DELETE requests, respectively.
MapMethods: Creates an endpoint that handles multiple HTTP methods.
MapControllerRoute, MapAreaControllerRoute: Used for configuring MVC/Razor Pages controllers.
MapFallbackToFile: Used to specify a default file to serve when no other endpoint matches.
 
Code: Detailed Explanation
//enable routing
app.UseRouting();
 
//creating endpoints
app.UseEndpoints(endpoints =>
{
    //add your endpoints here
    endpoints.MapGet(“map1”, async (context) => {
       await context.Response.WriteAsync(“In Map 1”);
    });
 
    endpoints.MapPost(“map2”, async (context) => {
       await context.Response.WriteAsync(“In Map 2”);
    });
});
 
app.Run(async context => {
    await context.Response.WriteAsync($”Request received at {context.Request.Path}”);
});
 
app.UseRouting();: This line activates routing middleware. It sets up the machinery to analyze incoming requests and match them against your defined endpoints.
app.UseEndpoints(endpoints => { … });: This lambda expression configures the endpoints of your application:
endpoints.MapGet(“map1”, …);: Registers a GET endpoint that responds to the path “/map1” with the text “In Map 1”.
endpoints.MapPost(“map2”, …);: Registers a POST endpoint for the path “/map2”, responding with “In Map 2”.
app.Run(async context => { … });: This is a fallback terminal middleware. If no other endpoint matches the request (e.g., if you visit “/map3”), it will execute this code, writing the requested path to the response.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply