0

I'm using ApiController and I can't get the call to return anything other than XML.

public class GuideController : ApiController
{
    [AcceptVerbs("GET")]

    [HttpGet]
    public string Get()
    {
        Item item = Item.GetTestData();
        string json = JsonConvert.SerializeObject(item);
        return json;
    }
}

Ideally, I want to return JSON normally but I'd settle for returning raw strings instead of XML wrapped ones.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Gianthra
  • 334
  • 2
  • 9
  • What is the accept header of the request? – Jason Boyd Dec 06 '16 at 18:14
  • 1
    Possible duplicate of [How do I get ASP.NET Web API to return JSON instead of XML using Chrome?](http://stackoverflow.com/questions/9847564/how-do-i-get-asp-net-web-api-to-return-json-instead-of-xml-using-chrome) – Heretic Monkey Dec 06 '16 at 18:24
  • Also, it should not be necessary for you to serialize your object in the controller action. Actually, it isn't even a good idea. For one, you are taking an operation (serialization) that is best handled in a single place, higher in the pipeline, and copying it across each of your controller actions. The second issue is that you are hamstringing content negotiation. – Jason Boyd Dec 06 '16 at 18:25

3 Answers3

3

An easy way to make sure the api only returns JSON is to remove the xml formatter from the http configuration.

You can access the formatters in the WebApiConfig class

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        //Clear current formatters
        config.Formatters.Clear();

        //Add only a json formatter
        config.Formatters.Add(new JsonMediaTypeFormatter());

    }
}

UPDATE

Don't serialize the object in the controller. Just return the object as is. Web api will do that for you as you have attached the json formatter to the configuration.

public class GuideController : ApiController
{
    [AcceptVerbs("GET")]

    [HttpGet]
    public IHttpActionResult Get()
    {
        Item item = Item.GetTestData();
        return Ok(item);
    }
}
Marcus Höglund
  • 16,172
  • 11
  • 47
  • 69
0

Try setting the Accept header in the client. If you want to receive JSON, set

Accept: application/json

in your client. Hope that helps.

Ivan Vargas
  • 703
  • 3
  • 9
0

Try to return JSON explicitly.

[HttpGet]
public IHttpActionResult Get()
{
    Item item = Item.GetTestData();       
    return Json(item);
}
gnud
  • 77,584
  • 5
  • 64
  • 78