Attribute Routing in Asp.net Core

Attribute Routing in Asp.net Core
Attribute routing allows you to define routes directly on your controller classes and action methods using attributes:
[Route] Attribute: Specifies the base route template for the controller or action.
[HttpGet], [HttpPost], etc.: Indicate the HTTP method(s) the action should handle.

Code
// HomeController.cs
namespace ControllersExample.Controllers
{
    [Controller] // Marks the class as a controller
    public class HomeController
    {
        [Route(“home”)] // Routes for this action
        [Route(“/”)]
        public string Index()
        {
            return “Hello from Index”;
        }
 
        [Route(“about”)]
        public string About()
        {
            return “Hello from About”;
        }
 
        [Route(“contact-us/{mobile:regex(^\\d{10}$)}”)] // Route with constraint
        public string Contact()
        {
            return “Hello from Contact”;
        }
    }
}
 
// Program.cs (or Startup.cs)
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers(); // Enables MVC controllers
 
var app = builder.Build();
app.UseRouting();
app.MapControllers(); // Connects controllers to the routing system
app.Run();
 
HomeController: This is your controller class.
Index, About, Contact: These are action methods within the controller, each with a corresponding route.
[Route] Attributes: Define the routes for each action method.
[Controller] Attribute: Marks the class as a controller, making it discoverable by the framework.
builder.Services.AddControllers();: Registers MVC services and makes controllers available for dependency injection.
app.MapControllers();: Connects the routing system to your controllers, enabling them to handle requests.

Comments

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

Leave a Reply