Unsupported Media Type error when posting to Web API

Billson picture Billson · Jul 20, 2015 · Viewed 51.5k times · Source

Making a windows phone application and although I may easily pull from my Web Api I am having trouble posting to it. Whenever posting to the api I get the "Unsupported Media Type" error message and I'm not sure as to why it is happening considering the class I using as the base for my JSON post is the same as the one used in the api.

PostQuote (Post Method)

private async void PostQuote(object sender, RoutedEventArgs e)
        {
            Quotes postquote = new Quotes(){
                QuoteId = currentcount,
                QuoteText = Quote_Text.Text,
                QuoteAuthor = Quote_Author.Text,
                TopicId = 1019
            };
            string json = JsonConvert.SerializeObject(postquote);
            if (Quote_Text.Text != "" && Quote_Author.Text != ""){

                using (HttpClient hc = new HttpClient())
                {
                    hc.BaseAddress = new Uri("http://rippahquotes.azurewebsites.net/api/QuotesApi");
                    hc.DefaultRequestHeaders.Accept.Clear();
                    hc.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                    HttpResponseMessage response = await hc.PostAsync(hc.BaseAddress, new StringContent(json));
                    if (response.IsSuccessStatusCode)
                    {
                        Frame.Navigate(typeof(MainPage));
                    }
                    else
                    {
                        Quote_Text.Text = response.StatusCode.ToString();
                        //Returning Unsupported Media Type//
                    }
                }
            }
        }

Quotes and Topic (Model)

public class Quotes
    {
        public int QuoteId { get; set; }
        public int TopicId { get; set; }
        public string QuoteText { get; set; }
        public string QuoteAuthor { get; set; }
        public Topic Topic { get; set; }
        public string QuoteEffect { get; set; }
    }
    //Topic Model//
    public class Topic
    {
        public int TopicId { get; set; }
        public string TopicName { get; set; }
        public string TopicDescription { get; set; }
        public int TopicAmount { get; set; }
    }

Answer

Pedro Drewanz picture Pedro Drewanz · Jul 21, 2015

As you can see in this and this articles, you should set the media type when creating StringContent

new StringContent(json, Encoding.UTF32, "application/json");