Reputation: 813
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
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
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