4
votes

I have webapi controller with 2 action methods like so:

public List<AlertModel> Get()
{
    return _alertService.GetAllForUser(_loginService.GetUserID());
}

public AlertModel Get(int id)
{
    return _alertService.GetByID(id);
}

However, when I make a request to api/alerts I get the following error:

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'ekmSMS.Common.Models.AlertModel Get(Int32)' in 'ekmSMS.Web.Api.AlertsController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.

I have the following route set up in global.asax:

routes.MapHttpRoute("Api", "api/{controller}/{id}", new { id = UrlParameter.Optional });

Should this type of overloading work? And if it should what am I doing wrong?

EDIT

Although this question is about WebAPI, the controllers are part of a MVC3 project, these are the other MapRoutes:

routes.MapRoute("Templates", "templates/{folder}/{name}", new { controller = "templates", action = "index", folder = "", name = "" });    
routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller = "app", action = "index", id = UrlParameter.Optional });
1
Could we see all your MapHttpRoutes ? Sometimes it could be some interference within them. - Kévin Rapaille
@user854301 question is about Web API, not MVC. - tugberk
that's pretty interesting cuz the route parameter whose default value is UrlParameter.Optional is removed if it is not supplied so, action selection logic should have picked up the Get() action method here (for any request which comes to api/alerts). I'll try to repro the error. - tugberk
I answered below. Don't use UrlParameter.Optional for any Web API route. Use RouteParameter.Optional instead. Keep in mind that don't use anything under System.Web.Mvc for any Web API code. - tugberk

1 Answers

12
votes

The problem is that you used UrlParameter.Optional (which is an ASP.NET MVC specific type) instead of RouteParameter.Optional. Change your route as below and then it should work:

GlobalConfiguration.Configuration.Routes.MapHttpRoute(
    "Api",
    "api/{controller}/{id}",
    new { id = RouteParameter.Optional }
);