Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Routing behaving weirdly

My WebApiConfig.cs

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
        config.EnableQuerySupport();
    }
}

My controller file is:

namespace myApp.Data
{
  public class AccountController : ApiController
  {
    public List<User> XGetUsers()
    {
        List<User> Users;
        using (Entities db = new Entities())
        {
            var users = from u in db.Users select u;
            Users = users.ToList();
        }
        return Users;
    }

    // GET api/<controller>/5
    public string Get(int id)
    {
        return "value";
    }
  }
}

But whenever I tried to call localhost:51255/api/Account/XGetUsers I keep getting a 400 error:

{"Message":"The request is invalid.","MessageDetail":"The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.String Get(Int32)' in myApp.Data.AccountController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter."}

It seems that all calls are going to the method Get(int id). What is wrong?

like image 479
Old Geezer Avatar asked Dec 02 '25 05:12

Old Geezer


1 Answers

Your route is missing the action:

routeTemplate: "api/{controller}/{action}/{id}",

so it was thinking that {id} was XGetUsers.

like image 80
Mike Perrenoud Avatar answered Dec 03 '25 17:12

Mike Perrenoud