How can I require a querystring for certain routes in an Asp.Net Web API?
Controllers:
public class AppleController : ApiController
{
public string Get() { return "hello"; }
public string GetString(string x) { return "hello " + x; }
}
public class BananaController : ApiController
{
public string Get() { return "goodbye"; }
public string GetInt(int y) { return "goodbye number " + y; }
}
Desired routes:
/apple --> AppleController --> Get()
/apple?x=foo --> AppleController --> Get(x)
/banana --> BananaController --> Get()
/banana?y=123 --> BananaController --> Get(y)
Just do something like this:
That way it is one route, and covers all cases. You could factor each out as private methods as well for clarity.
Another method would be to add more routes, but since these are somewhat specific, you would have to add extra routes. For simplicity, I would say you change the methods
GetStringandGetIntto the same thing (likeGetFromIdso you can reuse a route:If you do not make these general enough, you could end up with a LOT of route entries. Another idea would be to put these into Areas to avoid route confilcts.