2013-05-02 4 views
8
HttpClient serviceClient = new HttpClient(); 
serviceClient.DefaultRequestHeaders.Add("accept", "Application/JSON"); 

HttpContent content = new StringContent(text); 
content.Headers.Add("content-type", "text/html"); 

var response = await serviceClient.PostAsync(new Uri(_serviceUrl), content); 

Questo è il mio codice. Voglio fare un POST, e impostare il tipo di contenuto in text/html, ma quando lo faccio ottengo l'errore sopra riportato.C# HttpClient, ottenendo errore Impossibile aggiungere valore perché l'intestazione 'content-type' non supporta più valori

Posso impostare il tipo di contenuto che sembra via content.Headers.ContentType ma non so come specificare "text/html" se lo faccio. Qualcuno può aiutare?

risposta

7

Non hai .NET 4.5 pronto, ma secondo HttpContentHeaders.ContentType e MediaTypeHeaderValue, dovrebbe apparire qualcosa di simile:

content.Headers.ContentType = new MediaTypeHeaderValue("text/html"); 
+4

content.Headers.ContentType = new MediaTypeHeaderValue ("text'/html ")" è stato accettato, forse è così. Il suo parametro è 'string mediaType'. – NibblyPig

+0

@ SLC quindi dovrebbe essere 'content.Headers.ContentType = new MediaTypeHeaderValue (" text/html ")'? – CodeCaster

+0

Credo di sì, non è un errore, ma chissà se sta mandando le intestazioni giuste. Di solito il tipo di contenuto include anche la codifica dei caratteri, ma l'aggiunta che genera un errore quindi sto ignorando per ora ... – NibblyPig

0
var settings = new JsonSerializerSettings() 
     { 
      DateFormatHandling = 
       DateFormatHandling.MicrosoftDateFormat 
     }; 
     var serializedString = JsonConvert.SerializeObject(data, settings); 

     var conent = new StringContent(serializedString); 
     conent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); 
     var response = await this.httpClient.PostAsync(requestUri, conent).ConfigureAwait(false); 

     T requestResult = default(T); 
     if (response.IsSuccessStatusCode) 
     { 
      response.EnsureSuccessStatusCode(); 
      requestResult = await response.Content.ReadAsAsync<T>(); 
     } 
+1

per favore aggiungi qualche spiegazione alla tua risposta, mostrando cosa fa il codice e come risolve il problema. Questo aiuterà gli altri in futuro –

Problemi correlati