NET Core : Routing - UseRouting vs UseEndpoints

Understanding the Difference Between Endpoint and Routing in ASP.NET Core

In the world of ASP.NET Core, the concepts of “routing” and “endpoints” are fundamental to directing HTTP requests to their appropriate destinations. While they are closely related, they serve distinct purposes and work together to ensure that your web application responds correctly to user requests. In this blog post, we’ll dive deep into these concepts, explore their differences, and see how they are implemented with practical examples.

Table of Contents

  1. Introduction to Routing in ASP.NET Core
  2. Understanding Endpoints
  3. Routing vs. Endpoints: Key Differences
  4. Setting Up Routing in ASP.NET Core
  5. Configuring Endpoints in ASP.NET Core
  6. Advanced Examples and Scenarios
  7. Conclusion

Introduction to Routing in ASP.NET Core

Routing in ASP.NET Core is a system that maps incoming HTTP requests to the corresponding application logic. It defines the URL patterns that the application recognizes and binds them to the appropriate controllers, actions, Razor Pages, or middleware.

Key Features:

  • Route Templates: Define the structure of URLs.
  • Route Parameters: Extract data from URLs.
  • Attribute Routing: Allows defining routes directly on controller actions.

Example:

app.UseRouting();

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

In this example, the default route pattern is {controller=Home}/{action=Index}/{id?}, which maps to a specific controller and action based on the URL structure.

Understanding Endpoints

Endpoints represent the actual handlers for requests that have been routed. An endpoint could be a controller action, a Razor Page, or a middleware delegate. Endpoints are the final destinations where the application processes the request.

Key Features:

  • Endpoint Mapping: Defines the actual request handlers.
  • Endpoint Middleware: Works with routing to select which endpoint should handle a request.

Example:


app.UseRouting();

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

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

In this example, the /hello endpoint is mapped to a delegate that responds with “Hello World!”, demonstrating how endpoints can be direct request handlers without involving a controller.

Routing vs. Endpoints: Key Differences

  • Routing is about defining URL patterns and extracting data from the URLs.
  • Endpoints are the specific handlers that process the requests matched by the routing system.

Routing sets up the framework to determine which requests should go where, while endpoints are the concrete actions that execute when those requests arrive.

Setting Up Routing in ASP.NET Core

Configuring routing in an ASP.NET Core application typically involves defining route templates in the Startup.cs file.

Example:


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

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

This setup directs ASP.NET Core to use routing middleware and defines a default route for controllers.

Configuring Endpoints in ASP.NET Core

Endpoints are configured within the UseEndpoints method, which is called after UseRouting.

Example:


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

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

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

Here, the /hello endpoint is a simple delegate, while the default controller route handles more complex URL patterns.

Advanced Examples and Scenarios

Attribute Routing

Attribute routing allows defining routes directly on actions and controllers, providing more flexibility and control.

Example:


[Route("products")]
public class ProductsController : Controller
{
    [Route("list")]
    public IActionResult List()
    {
        return View();
    }

    [Route("details/{id}")]
    public IActionResult Details(int id)
    {
        return View();
    }
}

Custom Middleware as Endpoints

You can create custom middleware to act as an endpoint for specific routes.

Example:


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

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapGet("/middleware-endpoint", async context =>
        {
            await context.Response.WriteAsync("Handled by custom middleware");
        });

        endpoints.MapControllers();
    });
}

Combining Conventional and Attribute Routing

ASP.NET Core allows combining conventional and attribute routing to leverage both routing mechanisms.

Example:


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

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

[Route("api/[controller]")]
public class OrdersController : Controller
{
    [HttpGet]
    public IActionResult GetAll()
    {
        return Ok(new List<string> { "Order1", "Order2" });
    }

    [HttpGet("{id}")]
    public IActionResult GetById(int id)
    {
        return Ok($"Order {id}");
    }
}

In this example, the OrdersController uses attribute routing, while the application also defines a conventional route.

Endpoint Middleware for Advanced Scenarios

You can use endpoint middleware for more advanced routing scenarios, such as applying specific middleware to certain endpoints.

Example:


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

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();

        endpoints.MapGet("/secure-endpoint", async context =>
        {
            if (context.User.Identity.IsAuthenticated)
            {
                await context.Response.WriteAsync("Secure content");
            }
            else
            {
                context.Response.StatusCode = 401;
            }
        });
    });
}

In this example, the /secure-endpoint checks for authentication before returning content.

Conclusion

Understanding the distinction between routing and endpoints is crucial for building robust ASP.NET Core applications. Routing sets the path for how requests are matched, while endpoints are the destinations where those requests are handled. By effectively configuring both, you can create a seamless and efficient request handling pipeline in your ASP.NET Core applications.

In summary:

  • Routing defines the URL patterns and maps them to actions.
  • Endpoints are the handlers that process the requests once routed.
Next Post Previous Post
No Comment
Add Comment
comment url