Can you have 2 GET methods with different types of parameters inside the same web api controller?

I have an asp.net web api controller with two GET methods. One takes a string parameter, and the other takes an int parameter. I have only the default route, which is set using the web api in place.

public HttpResponseMessage GetSearchResults(string searchTerm) { HttpResponseMessage response; //Do Work return response; } public HttpResponseMessage Get(int id) { HttpResponseMessage response; //Do Work return response; } 

Each time I pass an int value in the url, the GET method is called, which takes a string parameter. The GET method, which takes an int parameter, is never called.

Is it possible to have 2 GET methods with different types of parameters inside the same controller?

-Edit- The proposed duplicate question is different in that it asks about two methods with the same parameters - I ask about different types of parameters.

+7
c # asp.net-mvc asp.net-web-api asp.net-web-api2
source share
1 answer

Yes it is possible. Out of the box with the default setting, what you should work with assumes that you pass searchTerm as the query string parameter. However, if you try to pass it as part of a URL, for example, /api/myurl/blah , the default routing of the agreement will try to match it with the version of the int method and return an error. You will have to either edit the default configuration or use Attribute Routing .

In general, I find Congress-based MVC routing to be less useful in WebApi, so I usually disable it and use Attribute Routing .

To enable attribute routing, add

 config.MapHttpAttributeRoutes(); 

into WebApi configuration.

Then you can mark your methods as such

 [HttpGet] [Route("api/myobject/")] public HttpResponseMessage GetSearchResults(string searchTerm) { HttpResponseMessage response; //Do Work return response; } [HttpGet] [Route("api/myobject/{id:int}")] public HttpResponseMessage Get(int id) { HttpResponseMessage response; //Do Work return response; } 

Now you can call the first method with

 /api/myobject?searchTerm=blah 

and the second through

 /api/myobject/1 

and they should not collide.

However, if you want searchTerm be in the URL instead of query parameters, you can change the route to

 [Route("api/myobject/{searchTerm}")] 

The api/myobject/{id:int} route will catch all identifiers, and api/myobject/{searchTerm} will catch most. However, be careful with this, as if the URL was not encoded in the URL, strange things will tend to happen.

I don’t know exactly what URL formatting you are looking for, so I presented simple examples. The link I posted earlier goes deeper into attribute routing. This allows you to perform more complex routes than routing by convention, which WebApi inherited from MVC.

+14
source share

All Articles