In ASP.NET Core, creating custom routes allows developers to define specific URL patterns that map to controller actions. This flexibility enables the design of intuitive and user-friendly URLs, which can enhance the overall user experience. Custom routes can be implemented using both attribute routing and conventional routing.

Key Concepts of Custom Routing

  • Route Templates: Custom routes are defined using route templates that specify the URL structure, including parameters and constraints.
  • Route Parameters: Parameters can be included in the route to capture dynamic values from the URL.
  • Constraints: Constraints can be applied to route parameters to restrict the types of values that can be matched.

Implementing Custom Routes

Below are examples of how to create custom routes using both attribute routing and conventional routing in an ASP.NET Core application.

1. Custom Routes with Attribute Routing

Attribute routing allows you to define routes directly on your controller actions using attributes. This method provides clear and concise routing definitions.

        
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
// Custom route for getting all products
[HttpGet("all")]
public IActionResult GetAllProducts()
{
return Ok("Returning all products.");
}

// Custom route for getting a product by name
[HttpGet("byname/{name}")]
public IActionResult GetProductByName(string name)
{
return Ok($"Returning product with name: {name}");
}

// Custom route for creating a product
[HttpPost("create/{name}")]
public IActionResult CreateProduct(string name)
{
return CreatedAtAction(nameof(GetProductByName), new { name }, $"Product {name} created.");
}
}

Explanation of Attribute Routing Example

In the example above:

  • Base Route: The base route for the ProductsController is defined as api/products.
  • GetAllProducts Action: The custom route api/products/all is defined for retrieving all products.
  • GetProductByName Action: The custom route api/products/byname/{name} captures the name parameter from the URL.
  • CreateProduct Action: The custom route api/products/create/{name} allows creating a product with the specified name.

2. Custom Routes with Conventional Routing

Conventional routing allows you to define a set of routes in a centralized manner, typically in the Startup class. Below is an example of how to set up custom routes using conventional routing.

        
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}

app.UseHttpsRedirection();
app.UseRouting();

app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
// Custom route for getting products by category
endpoints.MapControllerRoute(
name: "productsByCategory",
pattern: "api/products/category/{category}",
defaults: new { controller = "Products", action = "GetByCategory" });

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

Explanation of Conventional Routing Example

In the example above:

  • Custom Route: The custom route api/products /category/{category} is defined to map to the GetByCategory action in the ProductsController.
  • Default Route: The default route is set up to handle requests that do not match any custom routes, directing them to the Home controller and the Index action.

Conclusion

Creating custom routes in ASP.NET Core enhances the flexibility and usability of your web applications. Whether using attribute routing for clear, action-specific routes or conventional routing for centralized route management, developers can design intuitive URL structures that improve user experience and maintainability. By leveraging these routing techniques, you can create a more organized and user-friendly API or web application.