1

In my ApiController I need to handle this requests:

GET: api/User?role=theRole
GET: api/User?division=?theDivision
...
GET: api/User?other=stringValue

All these requests could be handled via a method like:

public HttpResponseMessage Get(String stringParam)

but obviously I cannot use overloading...

How can I solve this situation? Should I use a single method with optional parameters?

1
  • you may consider encoding all your parameters into one: GET: api/User?stringParam=role%20theRole ..... Commented Jul 6, 2015 at 13:11

2 Answers 2

2

According to this answer: https://stackoverflow.com/a/12620238/632604 you can write your methods like this:

public class UsersController : ApiController
    {

        // GET api/values/5
        public string GetUsersByRole(string role)
        {
            return "Role: " + role;
        }

        public string GetUsersByDivision(string division)
        {
            return "Division: " + division;
        }
    }

And Web API will route the requests just like you required:

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, you only need to prefix the name of the method with 'Get'. The routing mechanism will use query string parameters to map to the actual method.
0

One thing that you could consider doing would be modifying the default routes in your WebApiConfig file, you'll see how the default route is set as

routes.MapHttpRoute( name: "API Default", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } );

Change this to

routes.MapHttpRoute( name: "API Default", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } );

You could then tag each web API action with the correct HTTP action such as [HttpGet]. To learn more about routing and handling multiple HTTP actions in Web API take a look at http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.