Asp.net core 2.2 api routing

Viewed 80

In asp.net core 2.2 i have test api controller class and i have 2 get methods :

[Route("api/[controller]")]
[ApiController]
public class testController : Controller
{
    // GET: api/test
    [HttpGet]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/test/5
    [HttpGet("{id}")]
    public string Get(int id)
    {
       
        return "value";
    }
   ....
}

How to use this route api/test?id=1 for get method by id ?

1 Answers

How to use this route api/test?id=1 for get method by id ?

Use Route Attribute.

Route templates applied to an action that begin with / or ~/ don't get combined with route templates applied to the controller.

[FromQuery] - Gets values from the query string.

[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{

    //test url:   /api/test?id=7 
    [HttpGet("/api/test")]  // will ignore "api/[controller]" with "/"
    public int Test([FromQuery]int id)
    {
        return id;
    }

    .....
}

Test of result in .Net Core 2.2 API

enter image description here

Related