Web API Error: Failed to serialize the response body for content type

Error:

The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.

 
Workaround:
Just add the following code in WebApiConfig.cs –

var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);

Hope this helps!

Optional Parameters in Web API

Let us see how to make one or more parameters as optional in Web API.

[HttpGet]
[Route("Vehicles/GetDetails/{CompanyID}/{VehicleType}/{ModelNo}")]
public HttpResponseMessage GetDetails(String CompanyID, string VehicleType, string ModelNo)
{
    ...
}

Usually this method can be called like –

http://127.0.0.2:9966/Vehicles/GetDetails/101/SUV/DK999

If we want to make VehicleType as optional and pass it as null value like below, it will throw an error.

http://127.0.0.2:9966/Vehicles/GetDetails/101//DK999

 
This can be accomplished by moving all the optional parameters to last, assigning them a default value and passing them as separate values in the URL.
The method should be modified as –

[HttpGet]
[Route("Vehicles/GetDetails/{CompanyID}/{ModelNo}")]
public HttpResponseMessage GetDetails(String CompanyID, string ModelNo, string VehicleType = "ALL")
{
    ...
}

Then we can call the method as –

http://127.0.0.2:9966/Vehicles/GetDetails/101/DK999?VehicleType=SUV

We can also add it to body as well.