I am using Web Api 2.0 along 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 - When I call
http://blabla/api/partes
it gives me404 NOT FOUND
If I remove the parameter from the action:
public IHttpActionResult Get()
{
try
{
using (HornosContext db = new HornosContext())
{
return Ok(db.Partes.ToList());
}
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
and command to call the method like this: http://blabla/api/partes
It works.
Why is Web API not identifying the id as an optional value?
EDIT:
I know that 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 a duplicate the problem has to do with the order of registration of the routing configurations, here I solved it by specifying a default value to the action parameter (see answer below)
If you use
Web Api 2
use attributes to map using the[Route]
in this way you could create two action receiving or not theid
Attribute Routing in ASP.NET Web API 2
I just had to specify a default value to the method parameter and it worked