2015-07-20 71 views
7

製作Windows Phone應用程序,雖然我可以輕鬆地從我的Web Api拉出來,但我無法發佈到它。無論何時發佈到api,我都會收到「不支持的媒體類型」錯誤消息,我不確定爲什麼發生這種情況,因爲考慮到我使用的類作爲我的JSON文章的基礎,與api中使用的類相同。發佈到Web API時不支持的媒體類型錯誤

PostQuote(POST方法)

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// 
        } 
       } 
      } 
     } 

行情和主題(型號)

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; } 
    } 

回答

24

正如你在thisthis文章中看到,你應該在創建的StringContent

時設置的媒體類型
new StringContent(json, Encoding.UTF32, "application/json"); 
+4

不知何故,它不適用於Encoding.UTF32。 Encoding.UTF8確實有效。任何解釋? – MichaelD

+0

什麼是錯誤? –

+0

沒有錯誤,值不會被分析到模型中(它們保持爲空) – MichaelD

1

我在工作時發現了這個問題一個快速和骯髒的反向代理。我需要表單數據而不是JSON。

這對我來說訣竅。

string formData = "Data=SomeQueryString&Foo=Bar"; 
var result = webClient.PostAsync("http://XXX/api/XXX", 
     new StringContent(formData, Encoding.UTF8, "application/x-www-form-urlencoded")).Result; 
相關問題