0

I want to implement a custom action in a Web API controller that takes multiple arguments with ASP.Net MVC 4 Web API framework.

 public class APIRepositoryController : ApiController
{
    ...
    [HttpGet, ActionName("retrieveObservationInfo")]
    public ObservationInfo retrieveObservationInfo(
                    int id, 
                    String name1, 
                    String name2)
    {
        //...do something...
        return ObservationInfo;
    }
    ...
}

Such that I can call a URL in the web browser like:

"http://[myserver]/mysite/api/APIRepository/retrieveObservationInfo?id=xxx&name1=xxx&name2=xxx"

However, this has never worked.

Is there anything else I need to configure, e.g. WebAPI routing? Currently I just use the default WebApiConfig.cs.

Thanks in advance

1 Answer 1

4

By default Web API will dispatch actions based on HTTP verb rather than action name, in your case:

GET http://[myserver]/mysite/api/APIRepository/?id=xxx&name1=xxx&name2=xxx

To dispatch based on action name (like you want), you need to add the following route before the default route:

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

Note that you currently cannot (at least not without hacks) combine verb-based and action-name routing in a single controller reliably. You can read more about Web API routing here.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.