Currently, my ApiController
s 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;
JsonResult
instead ofHttpResponseMessage
, then you can return aJson
object, like this:return Json(model)
– Hindsreturn Ok(model)
– IsolationCannot implicitly convert type 'System.Web.Http.Results.JsonResult<MyCarModel>' to 'System.Web.Mvc.JsonResult'
– LidoSystem.Web.Mvc.JsonResult
, if your classe inherits fromSystem.Web.Mvc.Controller
, or you can maintain theHttpResponseMessage
and usereturn Request.CreateResponse(HttpStatusCode.OK, model)
– Hinds