web-api
  1. web-api-attribute-routing

Attribute Routing - (Web API Attribute Routing)

Attribute Routing is a way of defining routes for Web API controllers and actions by using attributes. With attribute routing, you can define routes in a more declarative way, which can make it easier to read, write, and maintain your Web API code.

Syntax

To use attribute routing in Web API, you can decorate controller actions with the [Route] attribute. Here is an example of using attribute routing in a Web API controller:

[Route("api/[controller]")]
public class MyController : ControllerBase
{
  [HttpGet("{id}")]
  public IActionResult Get(int id)
  {
    // Get the data from the service
    var data = GetData(id);

    // Return the response
    return Ok(data);
  }
}

Example

Here is an example of using attribute routing in a Web API controller:

[Route("api/[controller]")]
public class MyController : ControllerBase
{
  [HttpGet("{id}")]
  public IActionResult Get(int id)
  {
    // Get the data from the service
    var data = GetData(id);

    // Return the response
    return Ok(data);
  }

  [HttpPost]
  public IActionResult Post([FromBody] MyModel model)
  {
    // Save the data to the service
    SaveData(model);

    // Return the response
    return Ok();
  }
}

Output

When you make a GET request to http://localhost:5000/api/My/1, you should receive a response that looks like this:

{
  "id": 1,
  "name": "Hello, World!"
}

When you make a POST request to http://localhost:5000/api/My with a JSON body that looks like this:

{
  "id": 2,
  "name": "Hello, World Again!"
}

You should receive a 200 OK response.

Explanation

In the example code, we define a Web API controller called MyController that uses attribute routing to define its routes. The Get action has a URL template of "{id}", which maps to the id parameter in the action method. The Post action has no URL template, but uses the [FromBody] attribute to indicate that the action should read the model from the request body.

Published on: