Language: EN

csharp-carter

Simplifying Routing in ASP.NET with Carter

Carter is a C# library designed to facilitate routing in ASP.NET Core applications.

This library aims to simplify the creation of RESTful APIs through a smoother setup and a more organized structure, eliminating the need to write repetitive and verbose routing code.

Main features,

  • Modularity: Allows grouping of routes and controller logic into modules, making code organization easier.
  • Simplicity: Reduces the amount of code needed to define routes and controllers.
  • Integration with ASP.NET Core: Works seamlessly with the ASP.NET Core infrastructure and middleware.

For more details about Carter, explore the repository on GitHub, where you’ll find additional documentation and usage examples.

Installation and Configuration

To start using Carter in your ASP.NET Core project, install the Carter NuGet package using the .NET CLI:

Install-Package Carter

Alternatively, you can add the package via the NuGet Package Manager in Visual Studio.

How to Use Carter

Configuration

First, in the Startup.cs file, you need to configure the services and middleware to use Carter. Make sure to add the Carter service in the ConfigureServices method and set up routing in the Configure method.

using Carter;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddCarter();

var app = builder.Build();

app.MapCarter();
app.Run();


public class HomeModule : ICarterModule
{
public void AddRoutes(IEndpointRouteBuilder app)
{
	app.MapGet("/", () => "Hello from Carter!");
}
}

This code snippet defines a HomeModule that implements the ICarterModule interface. Inside the AddRoutes method, a GET route is configured at the root of the site (”/”), which returns the message “Hello from Carter!“.

If you run the application and open the address localhost(where xxxx is the configured port), you will see this response from Carter.

Defining a Module

Carter simplifies the definition of routes and controllers by allowing you to group them into modules. A module in Carter is a class that inherits from CarterModule. You can define routes and controller logic within this module.

// Modules/ProductModule.cs
public class ProductModule : ICarterModule
{
    public void AddRoutes(IEndpointRouteBuilder app)
    {
        app.MapGet("/products", async (HttpRequest req) =>
        {
            var products = new[]
            {
                new { Id = 1, Name = "Product 1", Price = 10.0 },
                new { Id = 2, Name = "Product 2", Price = 20.0 }
            };
            return products;
        });

        app.MapGet("/qs", async (HttpRequest req) =>
        {
            var ids = req.Query.AsMultiple<int>("ids");
            return $"It's {string.Join(",", ids)}";
        });
    }
}

Within this method, two routes are defined:

  • Route /products: This route handles GET requests to /products and returns a list of products in JSON format.
  • Route /qs: This route handles GET requests to /qs and retrieves multiple values from a query string called ids. It then returns those values in a comma-separated string.