Search code examples
c#.net-coreasp.net-web-api2.net-6.0

.NET 6 best way to differentiate a route in the same controller class


I have an API controller say TestController.

I have the following route definition: api/[controller] on class level and I can call the default get method as follows: .../api/test

I want to have another method in the same controller, I also want to call it with Get and the link should be as follows: .../api/test-abc

What is the best way to differentiate this second method within the same controller class.


Solution

  • For test-abc, you can configure the Route attribute as ~/api/test-abc to override the controller base route. See this link for details.

    [Route("api/[controller]")]
    public class TestController : ControllerBase
    {
      public IActionResult Get() 
      {
        // ...
      }
    
      [HttpGet]
      [Route("~/api/test-abc")]
      public IActionResult GetAbc()
      {
        // ...
      }
    }
    

    This approach changes only the URL of the "test-abc"-action; all other actions of the controller use the base URL configured on class level.