Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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; 
like image 560
cool breeze Avatar asked Mar 02 '18 16:03

cool breeze


People also ask

How do I return a JSON response in C#?

ContentType = "application/json; charset=utf-8"; Response. Write(myObjectJson ); Response. End(); So you return a json object serialized with all attributes of MyCustomObject.

How do I return a view in Apicontroller?

So, if you want to return a View you need to use the simple ol' Controller . The WebApi "way" is like a webservice where you exchange data with another service (returning JSON or XML to that service, not a View). So whenever you want to return a webpage ( View ) for a user you don't use the Web API.


2 Answers

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);     } 
like image 83
Ashiquzzaman Avatar answered Oct 10 '22 19:10

Ashiquzzaman


The XML is returned instead JSON because the caller is requesting XML. The returned format can be forced to JSON using a filter that adds the header you need and lets MVC resolve the JSON.

public class AcceptHeaderJsonAttribute : ActionFilterAttribute {     public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)     {         actionContext.Request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));         } } 

So you can decorate the method you want to force a JSON response with this attribute and keep the same global JSON configuration and serialization as any other method.

like image 39
animalito maquina Avatar answered Oct 10 '22 20:10

animalito maquina