1

I have 3 WEB API and 2 of them are working. The third one is not working although it is similar the other ones.

My Controller:

public class LNAXController : ApiController
{
    [HttpGet]
    public IEnumerable<State> States()
    {
        using (ApplicationDbContext db = new ApplicationDbContext())
        {
            return db.States.Where(s => s.Country.Code == "USA").OrderBy(o => o.Name).ToList();
        }
    }

    [HttpGet]
    public IEnumerable<State> States(string countryCode)
    {
        using (ApplicationDbContext db = new ApplicationDbContext())
        {
            return db.States.Where(s => s.Country.Code == countryCode).OrderBy(o => o.Name).ToList();
        }
    }

    [HttpGet]
    public IEnumerable<City> Cities(int stateId)
    {
        using (ApplicationDbContext db = new ApplicationDbContext())
        {
            return db.Cities.Where(c => c.State.Id == stateId).OrderBy(o => o.Name).ToList();
        }
    }
}

The first and second API, return result using following urls I type in browser:

http://localhost:58211/api/lnax/states
http://localhost:58211/api/lnax/states/USA

But the 3rd one returns error when I use this url: http://localhost:58211/api/lnax/cities/5

No HTTP resource was found that matches the request URI 'http://localhost:58211/api/lnax/cities/5'.

No action was found on the controller 'LNAX' that matches the request.

Edit:

This is my configuration code:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { action = "Get", id = RouteParameter.Optional }
        );
    }
}
FLICKER
  • 6,439
  • 4
  • 45
  • 75

2 Answers2

0

I suppose you have configured the Web API routing something like like:

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

You have to let it know that you want to assign countryCode to stateId. You could use [FromUri] attribute to the argument:

[HttpGet]
public IEnumerable<City> Cities([FromUri(Name ="countryCode")]int stateId)
{
    using (ApplicationDbContext db = new ApplicationDbContext())
    {
        return db.Cities.Where(c => c.State.Id == stateId).OrderBy(o => o.Name).ToList();
    }
}
Mike Mat
  • 632
  • 7
  • 15
0

Considering your configuration, the problem is the name of parameter.

In your configuration you have id as parameter but in your method you have stateId, so you need to use the parameter transformation

Change your method signature as:

public IEnumerable<City> Cities([FromUri(Name = "id")]int stateId)