Use mapcontrollerroute and mapget together in asp net core

Introduction

ASP.NET is a popular language used for building web applications. It provides a powerful framework for developing dynamic and interactive websites. One of the key features of ASP.NET is its routing system, which allows to how URLs are to specific actions or controllers.

Using MapControllerRoute

MapControllerRoute is a in ASP.NET that allows you to define routes for your controllers. It is typically used in the method of the Startup class. Let's take a look at an example:


public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseRouting();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
}

In the above example, we are using the MapControllerRoute method to define a default route. This route will be used when no specific route is specified. It maps the URL pattern {controller=Home}/{action=Index}/{id?} to the corresponding controller and action.

Using MapGet

MapGet is method in ASP.NET that allows you to define routes for HTTP GET . It is typically used in the Configure method of the Startup class. Let's see an example:


app.UseEndpoints(endpoints =>
{
    endpoints.MapGet("/hello", async context =>
    {
        await context.Response.WriteAsync("Hello, !");
    });
});

In the above example, we are using the MapGet method to define a route for the URL “/hello”. When a GET request is made to this URL, the specified action will be executed. In this case, it will write “Hello, World!” to the response.

Using MapControllerRoute and MapGet

Now, let's see how we can use both MapControllerRoute and MapGet methods together in ASP.NET Core:


app.UseRouting();

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");

    endpoints.MapGet("/hello", async context =>
    {
        await context.Response.WriteAsync("Hello, World!");
    });
});

In the above example, we have defined a default route using MapControllerRoute and a specific route for the URL “/hello” using MapGet. This means that when a request is made to “/hello”, the specified action in MapGet will be executed. For any other requests, the default route will be used.

Conclusion

In this article, we have explored how to use the MapControllerRoute and MapGet methods in ASP.NET Core. These methods allow you to define routes for your controllers and handle HTTP GET requests, respectively. By combining these methods, you can create a flexible and powerful routing system for your ASP.NET Core applications.

Rate this post

Leave a Reply

Your email address will not be published. Required fields are marked *

Table of Contents