c# - Route attribute routing with query strings when there are multiple routes -


i have this:

[httpget] [route("cats")] public ihttpactionresult getbycatid(int catid)  [httpget] [route("cats")] public ihttpactionresult getbyname(string name) 

they called providing query string eg cats?catid=5

however mvc web api can't have multiple routes same (both routes "cats".

how can work mvc web api recognize them separate routes? there can put route property? says ? invalid character put route.

you can merge 2 actions in question one

[httpget] [route("cats")] public ihttpactionresult getcats(int? catid = null, string name = null) {      if(catid.hasvalue) return getbycatid(catid.value);      if(!string.isnullorempty(name)) return getbyname(name);      return getallcats(); }  private ihttpactionresult getallcats() { ... }  private ihttpactionresult getbycatid(int catid) { ... }      private ihttpactionresult getbyname(string name) { ... } 

or more flexibility try route constraints

referencing attribute routing in asp.net web api 2 : route constraints

route constraints

route constraints let restrict how parameters in route template matched. general syntax "{parameter:constraint}". example:

[route("users/{id:int}"] public user getuserbyid(int id) { ... }  [route("users/{name}"] public user getuserbyname(string name) { ... } 

here, first route selected if "id" segment of uri integer. otherwise, second route chosen.


Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -