Reputation: 17658
I am trying to implement a basic routing in my .net core web api.
I have a controller like this:
[Route("api/[controller]")]
public class FooController : Controller
{
//out of the box
[HttpGet("[action]")] //get the list
public IEnumerable<Foo> Get()
{
//omitted
}
//added: request detail request///
[HttpGet("[action]/{fooid}")]
public Foo Get(string fooid)
{
//omitted
}
}
I trying to make the following routes work:
One for the details:
http://localhost:2724/api/Product/Get?fooid=myfoo1
And a general one for the listing:
http://localhost:2724/api/Product/Get
The problem is that the call with the ?fooid=
ends up at the IEnumerable
version and I can't seem to get it right.
I tried various syntactic variations to overcome this, e.g.: [HttpGet("{fooid}")]
but this doesn't seem to help.
I know I can just rename the method, but I am doing this as an exercise.
I also know it's not done to ask for documentation, but any help on this matter is welcome.
I also tried to add a route:
app.UseMvc(routes =>
{
routes.MapRoute( //default
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
routes.MapRoute(
name: "fooid",
template: "{controller=Home}/{action=Index}/{fooid?}");
routes.MapSpaFallbackRoute(
name: "spa-fallback",
defaults: new { controller = "Home", action = "Index" });
});
I tried some of the methods as described here, but no success.
Can you give me some directions?
Upvotes: 2
Views: 810
Reputation: 8662
Your URL for the parameter version is incorrect. It needs to be the same as you have written in the HttpGet attribute e.g.
http://localhost:2724/api/Product/Get/myfoo1
If you do want the parameter to be passed as ?fooId=myFoo then you need to declare your method as:
[HttpGet("[action]")]
public Foo Get([FromUri]string fooId)
{
...
}
Upvotes: 5