Route vs Verb in .NetCore


In ASP.NET Core, routing and the use of HTTP verb attributes like [HttpPost("login")] serve to direct requests to specific actions, but they are implemented differently. Let’s break down the differences and how they relate.

Route vs Verb in .NetCore

1. Route Attribute ([Route])

The [Route] attribute is used to define how the URL path is mapped to a controller action. It is part of attribute routing in ASP.NET Core. It allows you to explicitly define the URL pattern for your controller or specific action methods.

Example

[Route("api/users")]
public class UsersController : ControllerBase
{
    [Route("profile/{id}")]
    public IActionResult GetProfile(int id)
    {
        return Ok("User profile " + id);
    }
}
  • The [Route] attribute here defines the URL structure. For example, api/users/profile/{id} maps to the GetProfile method.
  • The routing doesn’t care about the HTTP verb (e.g., whether it's a GET, POST, or PUT request) it just defines the path and any parameters (like {id}).

2. HTTP Verb Attribute (ex-[HttpPost("login")])

The HTTP verb attributes like [HttpPost], [HttpGet], etc., are used to define what type of HTTP request (e.g., GET, POST, PUT, DELETE) the action responds to. These attributes also support defining routes at the same time.

Example

public class AccountController : ControllerBase
{
    [HttpPost("login")]
    public IActionResult Login([FromBody] LoginModel model)
    {
        // Handle the login logic
        return Ok("Login successful");
    }
}
  • The [HttpPost("login")] attribute here defines that the Login method will only respond to POST requests and will only be accessible via the URL /login.
  • This attribute is both defining the route (/login) and specifying the HTTP verb (POST).
  •  


Prev Next

Top Articles

  1. What is JSON
  2. How to convert a javaScript object in JSON object
  3. Some Important JSON Examples
  4. Common JSON Interview Question