itsNino91
itsNino91

Reputation: 129

Multiple Parameter Route Web api

So I'm creating an api where the url should look like this : http://localhost:16769/api/query/2/John_Doe. When I run this url it takes me to my second Get function.

QueryController.cs

// GET api/query
public string Get(int id, string param)
{
    string output = "";
    output = JsonConvert.SerializeObject(null);
    return output;
}

// GET api/query/5
public string Get(int id)
{
    return "value";
}

The first parameter will always be an integer where the second will always be a string and both parameters are required for this get request to work. Here is my config file setup.

WebApiConfig.cs

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

Using the above url allows the output to be "value". If I comment out the second Get function I get the following error: No HTTP resource was found that matches the request URI 'http://localhost:16769/api/query/2/John_Doe'. No action was found on the controller 'Query' that matches the request. How can I set up my routes or methods to work with this pattern?

Upvotes: 0

Views: 1848

Answers (2)

Rajesh
Rajesh

Reputation: 7876

I guess you need to rename you parameter on the first method to be in sync with your routetemplate i.e. rather that using param as the variable name in first method replace that with paramString and see if it works

Upvotes: 1

peinearydevelopment
peinearydevelopment

Reputation: 11474

use attribute routing:

[RoutePrefix("api/query")
public QueryController: ApiController
{
  [Route("{id}/{param}")]
  public string Get(int id, string param)
  {
      string output = "";
      output = JsonConvert.SerializeObject(null);
      return output;
  }

  // GET api/query/5
  [Route("{id}")]
  public string Get(int id)
  {
      return "value";
  }
}

And then your route config can be put back to the default.

Upvotes: 1

Related Questions