Search code examples
jsonasp.net-mvc-4asp.net-web-apicontent-type

How can I get a JSON response instead of XML?


I just create a new WebApi project and keep the default controller :

public class ValuesController : ApiController
{ 
    // GET api/values/5
    public string Get(int id)
    {
        return "value";
    }

    //other services...
}

When I try to request it, I can't get a valid JSON result.

  • No specific header => application/xml result
  • Header with content-type assigned to application/json => application/xml result
  • Header with accept assigned to application/json gives me a correct response content-type but a malformed JSON : "value".

What is the way to get a valid JSON result ?


Solution

  • You will have to use JsonResult as your return type:

    public class ValuesController : ApiController
    { 
        // GET api/values/5
        public JsonResult Get(int id)
        {
            object returnObject;
    
            // do here what you need to get the good object inside returnObject
    
            return this.Json(returnObject, JsonRequestBehavior.AllowGet);
        }
    
        // other services...
    }