2

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?

1

1 Answer 1

5

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)
{
    ...
}
Sign up to request clarification or add additional context in comments.

2 Comments

Okay... that seems to fix it.Thank you.
One side mark: n asp .net core 2, [FromUri] seems depricated. See: stackoverflow.com/questions/36974734/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.