user1451111
user1451111

Reputation: 1943

ASP.NET Web API routing with action parameter

in the WebApiConfig.cs file of my Web API project I have replaced the default routing mapping to this one:

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

as I want controller and action combinations instead of a lot of GETs and POSTs.

The problem is this. I have a controller CityController with below 2 actions.

[HttpGet]
        public HttpResponseMessage GenderCount()
        {
            //Validate session and fetch gender related data of the city
            return Request.CreateResponse(HttpStatusCode.OK, genderData);                
        }

        [HttpGet]
        public HttpResponseMessage GenderCount(string cityID)
        {
            //Validate session and fetch gender related data of the city
            return Request.CreateResponse(HttpStatusCode.OK, genderData);                
        }

The {HostName}/api/City/GenderCount?cityID=4 API call works but when I try to issue the same API call in the {HostName}/api/City/GenderCount/4 format, it goes to the without-parameter 'GenderCount()' action.

Upvotes: 0

Views: 108

Answers (1)

Nishith Shah
Nishith Shah

Reputation: 393

If you already have a route prefix

[RoutePrefix("api/City")]

on your controller, try decorating your method with attribute routing.

[Route("GenderCount/{cityID}"]

OR

use full route path

[Route("api/City/GenderCount/{cityID}")]

Upvotes: 1

Related Questions