2015-07-20 68 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; 
相关问题