ASP.NET WEB API 2 Routing Woes

I was trying out ASP.NET WEB API 2 and I fumbled. I was caught off guard by the new Routing behavior. I created 2 controllers:

public class SampleController : ApiController
{
    [HttpGet]
    [Route("api/{controller}/{action}/{id}")]
    public Person GetPersonById(int id)
    {
        return new Person() { FirstName = "Serena", LastName = "Yeoh" };
    }

    [HttpGet]
    [Route("api/{controller}/{action}/{id}/{country}")]
    public Person CheckCountry(int id, string country)
    {
        // ...
    }
    // Other methods not shown for simplicity sake.
}

and

public class DummyController : ApiController
{
    [HttpGet]
    [Route("api/{controller}/{action}/{id}")]
    public Person GetPersonById(int id)
    {
        return new Person() { FirstName = "Serena", LastName = "Yeoh" };
    }

    [HttpGet]
    [Route("api/{controller}/{action}/{id}/{country}")]
    public Person CheckCountry(int id, string country)
    {
        // ...
    }
    // Other methods not shown for simplicity sake.
}

When I tried to access my API from the browser, I was greeted with a HTTP 404 Not Found. Using fiddler, I managed to capture the actual error message:

{"Message":"No HTTP resource was found that matches the request URI 'http://localhost:2937/Api/Sample/GetPersonById/1'.","MessageDetail":"No route providing a controller name was found to match request URI 'http://localhost:2937/Api/Sample/GetPersonById/1'"}

This error only appears when there are 2 controllers with methods that have same signatures. If the signatures are different, everything will execute fine.

I found that to fix the problem, I will need to hard-code the RoutePrefix on the classes like the following:

[RoutePrefix("api/Dummy")]
public class DummyController : ApiController

[RoutePrefix("api/Sample")]
public class SampleController : ApiController

and change the Route template on the methods

[Route("{action}/{id}")]
public Person GetPersonById(int id)

[Route("{action}/{id}/{country}")]
public Person CheckCountry(int id, string country)

While this solution works, I find it not very clean as I have to hard-code the controller's name in the RoutePrefix.

In case you are wondering, here's the Visual Studio generated WebApiConfig.cs file.

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

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

I do know that we can create new MapHttpRoute entries for every different method signature but I find that to be quite insane as well.

Are there any other solutions?

No comments:

Post a Comment

Popular Post