Curious-programmer
Curious-programmer

Reputation: 813

Api Controller Routing error - the parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32'

I have two httpGet methods in my api controller. I use attribute routing to differentiate between them. When I navigate to localHost/api/Lockers/availableLockers I get an error:

the parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Http.IHttpActionResult GetLocker(Int32)

In my Lockers api Controller:

 public IQueryable<Locker> GetLocker()
        {
            return db.Lockers;
        }


        [Route("availableLockers")]
        [HttpGet]
        public IQueryable<Locker> GetAvailableLockers()
        {
            return db.Lockers.Where(l => l.StudentId != null);
        }

[ResponseType(typeof(Locker))]
    public IHttpActionResult GetLocker(int id)
    {
        Locker locker = db.Lockers.Find(id);
        if (locker == null)
        {
            return NotFound();
        }

        return Ok(locker);
    }

What I tried:

Based on a previous Stackoverflow answer I added to my webAp.config

In webApi.config

config.MapHttpAttributeRoutes();

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

This does not change the error

Upvotes: 1

Views: 331

Answers (2)

Ankit K
Ankit K

Reputation: 1326

Add RoutePrefix attribute on your controller as below:

[RoutePrefix("api/Lockers")]
public class LockersController : ApiController
{

}

After adding RoutePrefix on your controller your route: localHost/api/Lockers/availableLockers will start working. Currently it is throwing exception because application is considering it as id=applicationLockers which expects last parameter as int

Upvotes: 1

Bob Dust
Bob Dust

Reputation: 2460

It was your routing attribute. It should have been:

    [Route("api/Lockers/availableLockers")]
    [HttpGet]
    public IQueryable<Locker> GetAvailableLockers()
    {
        return db.Lockers.Where(l => l.StudentId != null);
    }

Upvotes: 0

Related Questions