Discussions

Ask a Question
Back to All

Unsupported Media Error -- Can we get a simple C# PUT example that uses something other than REST SHARP?

I couldn't resist formatting my question in the Bruce Wilson style (that he hat-tipped back to me. Thanks Bruce ha)...

Can we get a simple C# REST PUT example that does not use REST Sharp. Maybe something that uses HttpClient?

I get Unsupported Media Type no matter what I do. I think it has to do with Encoding or Charset but I don't know which one to send....

This code is the latest I produced to get the Unsupported Media Error
static async Task createEvent(string id)
{
//ZEX18AB197
//ZPEX182820
var settings = new JsonSerializerSettings();
settings.TypeNameHandling = TypeNameHandling.Objects;

        // Create the client
        using (var client = new HttpClient())
        {
            // Format headers
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            //client.DefaultRequestHeaders.AcceptCharset.Add(new StringWithQualityHeaderValue("UTF8"));
            // Request token, and append to headers
            await AddTokenToHeaders(client);

            EventData eventNew = new EventData();
            var responseEvent = await client.GetAsync(baseUrl + EVENT_REST_QUERY + "/" + id);
            if (responseEvent.IsSuccessStatusCode)
            {
                // Deserialize response to DataContract
                eventNew = await responseEvent.Content.ReadAsAsync<EventData>();
            }
            EventFunctionData eventFunction = new EventFunctionData();
            eventFunction.Description = "TestFunc3";
            eventFunction.EventFunctionCode = "TestFunc3";
            eventFunction.EventFunctionId = "TestFunc3";
            eventNew.Functions.Add(eventFunction);


            string Serialized = JsonConvert.SerializeObject(eventNew);               
            HttpContent content = new StringContent(Serialized, System.Text.Encoding.Unicode, "application/json");
            //byte[] encodedBytes = System.Text.Encoding.UTF8.GetBytes(json);
            //System.Text.Encoding.Convert(System.Text.Encoding.UTF8, System.Text.Encoding.Unicode, encodedBytes);

            var response = await client.PutAsync(baseUrl + EVENT_REST_QUERY + "/" + id, content);
            if (response.IsSuccessStatusCode)
            {
                // Deserialize response to DataContract
                eventNew = await response.Content.ReadAsAsync<EventData>();
            }
            }
    }

This results in a Unsported Media Type error on PUT

Thanks