2012-10-03 19 views
8

Comprendo che l'API WEB utilizza la negoziazione del contenuto per Accept - Content-Type per restituire json o xml. Questo non è abbastanza buono e ho bisogno di essere in grado di decidere pragmaticamente se voglio restituire json o xml.Come restituire JSON da MVC WEB API Controller

Internet è invaso da esempi di utilizzo obsoleti HttpResponseMessage<T>, che non è più presente in MVC 4.

tokenResponse response = new tokenResponse(); 
response.something = "gfhgfh"; 

    if(json) 
    { 
     return Request.CreateResponse(HttpStatusCode.OK, response, "application/json"); 
    } 
    else 
    { 
     return Request.CreateResponse(HttpStatusCode.OK, response, "application/xml"); 
    } 

Come faccio a cambiare il codice di cui sopra in modo che funzioni?

risposta

23

Prova in questo modo:

public HttpResponseMessage Get() 
{ 
    tokenResponse response = new tokenResponse(); 
    response.something = "gfhgfh"; 

    if(json) 
    { 
     return Request.CreateResponse(HttpStatusCode.OK, response, Configuration.Formatters.JsonFormatter); 
    } 
    else 
    { 
     return Request.CreateResponse(HttpStatusCode.OK, response, Configuration.Formatters.XmlFormatter); 
    }  
} 

o, meglio ancora, per evitare di ingombrare il controller con tale codice infrastrutture impianto idraulico si potrebbe anche scrivere un formattatore supporti personalizzati ed eseguire questo test al suo interno.

+0

Giusto! Il mio errore è stato che il metodo Get() aveva un tipo di ritorno di tokenResponse. Grazie! – user1662812

Problemi correlati