Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The reason why you are hitting the cast exception is because the type information is lost from the client and server.</p> <p>One way to get your scenario to work is to do the following</p> <ol> <li>Use ObjectContent instead of StringContent so we let the formatter (i.e. JsonMediaTypeFormatter) to deal with the serialization and deserialization</li> <li>Turn on TypeNameHandling on both the client and server so that the type information will be send on the wire</li> </ol> <p>Server (WebApiConfig.cs):</p> <pre><code> config.Formatters.JsonFormatter.SerializerSettings.TypeNameHandling = Newtonsoft.Json.TypeNameHandling.All; </code></pre> <p>Client:</p> <pre><code> //Gets a list of various objects List&lt;object&gt; values = new List&lt;object&gt;(); values.Add(GetItem1()); //Returns a Dictionary&lt;string, string&gt; object values.Add(GetItem2()); //Returns a List&lt;string&gt; object values.Add(GetItem3()); //List&lt;KeyValuePair&lt;string, string&gt;&gt; var formatter = new JsonMediaTypeFormatter(); formatter.SerializerSettings.TypeNameHandling = Newtonsoft.Json.TypeNameHandling.All; var content = new ObjectContent&lt;List&lt;object&gt;&gt;(values, formatter); HttpResponseMessage postResult = client.PostAsync(baseURL, content).Result; </code></pre> <p>Sample Request Body:</p> <blockquote> <p>{"$type":"System.Collections.Generic.List<code>1[[System.Object, mscorlib]], mscorlib","$values":[{"$type":"System.Collections.Generic.Dictionary</code>2[[System.String, mscorlib],[System.String, mscorlib]], mscorlib","DictionaryKey1":"DictionaryValue1"},{"$type":"System.Collections.Generic.List<code>1[[System.String, mscorlib]], mscorlib","$values":["ListItem1"]},{"$type":"System.Collections.Generic.List</code>1[[System.Collections.Generic.KeyValuePair`2[[System.String, mscorlib],[System.String, mscorlib]], mscorlib]], mscorlib","$values":[{"Key":"KeyValuePairKey","Value":"KeyValuePairKeyValue"}]}]}</p> </blockquote>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload