Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading WebAPI controller with 2 Get methods

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 });
like image 936
jcvandan Avatar asked Dec 15 '22 21:12

jcvandan


1 Answers

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 }
);
like image 173
tugberk Avatar answered Jan 05 '23 11:01

tugberk