Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to distinguish query parameters from path parameters

I want to have to GET methods on my api, one with the Route with path parameters:

api/people/{personId}

and one with the Route with query parameters:

api/people?text=something

but if i put this code:

// GET: api/people/{personId}
[Route("api/people/{personId}")]
[HttpGet]
public HttpResponseMessage Get(long personId)
{
}

// GET: api/people?text=something
[Route("api/people")]
[HttpGet]
public HttpResponseMessage Get(string text)
{
}

And then try to open /api/people/1 it says wrong format and when I try to open /api/people?text=something it works.

I only have the default route defined:

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );

How can I have them both working? Define that if it's a path parameter go to the first one and if it's a query parameter go to second on?

like image 743
Vítor Martins Avatar asked Oct 07 '15 13:10

Vítor Martins


1 Answers

I just put this into Visual Studio 2015 using Web API 2 and it works fine. I did have to add the following lines (one for each controller method).

return Request.CreateResponse(HttpStatusCode.OK);

I also blew away the Default Route Config. The following urls work just fine

http://localhost:64377/api/people/1

http://localhost:64377/api/people?text=Hello

I hit both respective methods in my controller when I put these URLs in IE.

like image 92
Mr. B Avatar answered Oct 16 '22 08:10

Mr. B