Search code examples
c#asp.net-mvcasp.net-mvc-4asp.net-mvc-routing

Even though I have 2 dedicate HttpGet Actions defined in my controller, only one gets called even when the URL specifies 2 different Actions


I am trying to develop REST APIs on my server for a JS plugin as described in http://docs.annotatorjs.org/en/v1.2.x/storage.html. Two of the APIs I am required to develop are as follows:

  1. Index: Index functionality with path as /annotations and method as get. I have implemented this in a controller annotations(placed in a directory called api) as follows:

    [HttpGet]

    public IList annotations(long userID = 2)

  2. Search: Search functionality with path as /search and method as get again. My implementation in the same controller is as:

    [HttpGet] public AnnotationSearchResults search(int count, string uri)

The problem I am facing is, in case of both the following URLS: http://localhost:5555/api/Annotation/search?limit=20&uri=www.abc.com and http://localhost:5555/api/Annotation/annotations the method annotation gets called, though I am expecting the search method to be called. I am very to web development and trying hard to get this running since last 2 days. Please excuse me if this is a very basic and obvious question.


Solution

  • In your App_Start folder, there is a WebApiConfig.cs file. The route template here does not include an action by default. You will need to add the action route to get your desired output.

    The default route for Web API is

    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
    

    Add an {action} to the routeTemplate as shown below and the correct action urls will be hit.

    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }