0

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.

3
  • m wondering why my code is NOT beautified Commented Nov 29, 2017 at 13:29
  • 1
    It is unable to map the id route parameter. change action parameter from string cityID to string id or do the reverse and update the route itself. Commented Nov 29, 2017 at 13:32
  • @Nkosi your answer worked partly. in the 'reverse' case, the POST actions could not be found with 404 resource not found message. Why did you not put this as the actual answer instead of Comment? Commented Nov 30, 2017 at 6:51

1 Answer 1

1

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}")]
Sign up to request clarification or add additional context in comments.

4 Comments

The without parameter action method is invoked even after enabling attribute routing and decorating the action, as you advised.
I have also verified the namespace of the route attribute which is "System.Web.Http".
It is fixed now. I had to add [Route("api/City/GenderCount/{cityID}")] instead of only [Route("{cityID}")]. If you update your answer accordingly, I can accept it. Probably you assumed that my CityController already has [RoutePrefix("api/City")] linked with it.
@user1451111 Yes, I assumed that you have RoutePrefix. Edited my answer.

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.