I'm trying to use a web API method, but I'm not having much success.
In my Controller I have:
public class TestAPIController : ApiController
{
public string Get()
{
return "Hello World";
}
public Cours Get(int id)
{
using (SSDEntities Entity = new SSDEntities())
return Entity.Courses.SingleOrDefault<Cours>(a => a.ID == id);
}
In my Global.asax I have:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
routes.MapHttpRoute(
name: "ApiWithAction",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}", // URL with parameters
new { controller = "Home", action = "Index" } // Parameter defaults
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
The problem is, if I type /api/TestAPI I successfully see "Hello World", however, /api/TestAPI/7 gives the following exception message: The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.
I have 1 result from the database that matches the id "7", which it should be returning. I'm not sure what I'm doing wrong. Anyone can help?