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

Viewed 96

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.

3 Answers

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.

In .Net 6 by following Minimal API's

app.MapGet("api/test", () =>
{
 
    return "";
});
app.MapGet("api/test-abc", () =>
{
    return "";
});

By following Traditional Method

[Route("api")]
 public class TestController : ControllerBase
  { 
    [HttpGet("test")]
    public IActionResult Get() 
     {
       // ...
        return Ok();
     }

   [HttpGet("test-abc")]
    public IActionResult GetAbc()
     {
      // ...
        return Ok();
     }
 }

enter image description here

You can by defining the controllers route template like as below:

[Route("api/[controller]")]
public class TestController : Controller
{
   ...
}

So you can define a method like:

[HttpGet]
[Route("~/api/Test/Index")]
public IActionResult Index()
{
    return Foo.Bar();
}

[HttpGet]
[Route("~/api/Test/Index2")]
public IActionResult Index2()
{
    return Foo.Bar2();
}


[HttpGet]
public IActionResult Index3()
{
    return Foo.Bar3();
}

You can call it by ../api/test/index2 to use the method Index2 or ../api/test to use Index3.

This is for the standardized way to do, in your case you would use - instead of / at the Route("...") attribute.

If you use - you need to call ../api/test-index2

For further information take a look at documentation.

Related