4

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 });
4
  • Could we see all your MapHttpRoutes ? Sometimes it could be some interference within them. Commented Aug 3, 2012 at 11:33
  • @user854301 question is about Web API, not MVC. Commented Aug 3, 2012 at 12:26
  • 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. Commented Aug 3, 2012 at 12:28
  • 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. Commented Aug 3, 2012 at 12:42

1 Answer 1

12

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 }
);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.