2012-07-31 10 views
23

Mi chiedo se sia possibile restituire più tipi in un solo Web Api. Ad esempio, desidero che una API restituisca entrambi gli elenchi di clienti e ordini (questi due insiemi di dati possono o non possono riguardare l'uno con l'altro?In che modo l'API Web restituisce più tipi

risposta

33

Per tornare più tipi, è possibile avvolgere in tipo anonimo, ci sono due approcci possibili:

public HttpResponseMessage Get() 
{ 
    var listInt = new List<int>() { 1, 2 }; 
    var listString = new List<string>() { "a", "b" }; 

    return ControllerContext.Request 
     .CreateResponse(HttpStatusCode.OK, new { listInt, listString }); 
} 

Oppure:

public object Get() 
{ 
    var listInt = new List<int>() { 1, 2 }; 
    var listString = new List<string>() { "a", "b" }; 

    return new { listInt, listString }; 
} 

Ricordo anche che serializzatore XML non supporta i tipi anonimi. Quindi, è necessario assicurarsi che la richiesta dovrebbe avere intestazione:

Accept: application/json 

al fine di accettare formato JSON

+2

Nota: la richiesta accetta deve essere application/json, poiché il serializzatore xml risponderà con un errore, non sapendo cosa fare. – fionbio

0

È necessario utilizzare il serializzatore JsonNetFormatter, poiché il serializzatore predefinito- DataContractJsonSerializer non può serializzare . tipi anonimi

public HttpResponseMessage Get() 
{ 
    List<Customer> cust = GetCustomers(); 
    List<Products> prod= GetCustomers(); 
    //create an anonymous type with 2 properties 
    var returnObject = new { customers = cust, Products= prod }; 
    return new HttpResponseMessage<object>(returnObject , new[] { new JsonNetFormatter() }); 
} 

si potrebbe ottenere JsonNetFormatter da HERE

+0

im ottenere un errore sul HttpResponseMessage (e anche il JsonNetFormatter ma credo di sapere il motivo per cui sono lì) dicendo "Il tipo non generico 'System.Net.Http.HttpResponseMessage' non può essere utilizzato con argomenti tipo". Qualche idea? – Matt

+0

Questo codice funzionerà su API Web ASP.NET beta –

Problemi correlati