Devsined
Devsined

Reputation: 3521

Web Api 2 MapHttpRoute is not working and is forcing me to use query strings

Hi I have customs config.Routes.MapHttpRoute but the API is forcing me to use query string as parameter instead regular parameters separated by / such has this ...api/data/2/23.

If I call my API as ...api/collectdata/1 it does not work but if I call like this it works ...api/collectdata?researchid=1

This what I have in my WebApiConfig

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

            config.Routes.MapHttpRoute(
                name: "CollectDataFromPets",
                routeTemplate: "api/collectdata/{researchid}");

And my controller looks like this:

public IHttpActionResult CollectData(int researchId)
          {
              try
              {
                  service.SaveDataByResearchId(researchId);
                  return Ok(new { Message = "Data collected and saved" });
              }
              catch (Exception e)
              {
                  return new CustomError(e.Message,Request);
              }
          }

Upvotes: 0

Views: 2220

Answers (1)

Filip W
Filip W

Reputation: 27187

  1. Route order matters. Your generic (DefaultApi) route has to be declared last since it's "greedy" - otherwise it will catch all the requests, preventing other routes from kicking in

  2. Your specific route doesn't have a controller defined, you will need to modify it to:

        config.Routes.MapHttpRoute(
            name: "CollectDataFromPets",
            routeTemplate: "api/collectdata/{researchid}",
            defaults: new {controller = "CollectData"} //or whatever your controller name is
        );
    

Upvotes: 2

Related Questions