How to return JSON in an ApiController for a single method?

cool breeze picture cool breeze · Mar 2, 2018 · Viewed 57k times · Source

Currently, my ApiControllers are returning XML as a response, but for a single method, I want to return JSON. i.e. I can't make a global change to force responses as JSON.

public class CarController : ApiController
{  
    [System.Web.Mvc.Route("api/Player/videos")]
    public HttpResponseMessage GetVideoMappings()
    {
        var model = new MyCarModel();    
        return model;
    }
}

I tried doing this, but can't seem to convert my model to a JSON string correctly:

var jsonString = Json(model).ToString();    
var response = this.Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
return response;

Answer

Ashiquzzaman picture Ashiquzzaman · Mar 2, 2018

If you can't make a global change to force responses as JSON, then try:

[Route("api/Player/videos")]
public HttpResponseMessage GetVideoMappings()
{
    var model = new MyCarModel();
    return Request.CreateResponse(HttpStatusCode.OK,model,Configuration.Formatters.JsonFormatter);
}

OR

[Route("api/Player/videos")]
public IHttpActionResult GetVideoMappings()
{
    var model = new MyCarModel();
    return Json(model);    
}

If you want to change globally, then first go to YourProject/App_Start/WebApiConfig.cs and add:

config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(
config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml"));

at the bottom of the Register method.

Then try:

[Route("api/Player/videos")]
public IHttpActionResult GetVideoMappings()
{
    var model = new MyCarModel();
    return Ok(model);    
}