I am using Web Api 2.0 together with MVC 5
This is my WebApiConfig
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
This is my controller:
public class PartesController : ApiController
{
public IHttpActionResult Get(int? id)
{
try
{
using (HornosContext db = new HornosContext())
{
if (id == null || id == 0)
{
return Ok(db.Partes.ToList());
}
else
{
return Ok(db.HornosPartes.Where(ph => ph.IdHorno == id).Select(ph => ph.Parte).ToList());
}
}
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
}
- When calling
http://blabla/api/partes/1
It works - Calling
http://blabla/api/partes
gives me404 NOT FOUND
If I remove the parameter of the action:
public IHttpActionResult Get()
{
try
{
using (HornosContext db = new HornosContext())
{
return Ok(db.Partes.ToList());
}
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
and I'll call the method like this: http://blabla/api/partes
It works.
Why is the Web API not identifying the id as an optional value?
EDIT:
I know I can add attributes and more actions, but being something so simple, I would like this to work with the default routes.
In the question suggested as duplicate the problem has to do with the order of registration of the routing configurations, here I resolved it by specifying a predetermined value to the parameter of the action (see answer below)