Restful API GET failing with 'The parameters dictionary contains a null entry for parameter 'id' of non-nullable type' '

StackOverflow https://stackoverflow.com/questions/16511939

  •  21-04-2022
  •  | 
  •  

Question

I am getting the following error:

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.String Get(Int32)' in 'RecipeTracker.Controllers.StandardDirectionsController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.

I have this defined in my global file:

    protected void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup
        RouteTable.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = System.Web.Http.RouteParameter.Optional });
    }

This is my controller:

    App_Data.databaseDataContext _context = new App_Data.databaseDataContext();
    // GET api/<controller>
    public List<string> Get()
    {
        var direction = (from d in _context.ViewStandardDirections("-1")
                         select d.Direction);

        return direction.ToList();
    }

    // GET api/<controller>/5
    public List<Models.DirectionChoices> Get([FromUri]string q)
    {
        var choices = (from i in _context.ViewStandardDirections(q)
                       select new Models.DirectionChoices
                       {
                           text = i.Direction
                       });
        return choices.ToList();
    }

This is the url that I tried and failed:

http://localhost:9328/api/standarddirections/heat

If i remove the /heat part then it queries the database just fine. I added in the [FromUri] based on another posts suggestion but it behaves the same as it did without it.

Was it helpful?

Solution

The parameter name has to match the route:

 //public List<Models.DirectionChoices> Get([FromUri]string q)
   public List<Models.DirectionChoices> Get([FromUri]string id)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top