发布到Web API时出现不支持的媒体类型错误

Bil*_*son 28 .net c# json windows-phone asp.net-web-api

制作一个Windows手机应用程序,虽然我可能很容易从我的网络Api拉出来,但我很难发布到它.每当发布到api时,我都会收到"不支持的媒体类型"错误消息,并且我不确定为什么会发生这种情况,因为我使用的类作为我的JSON帖子的基础与api中使用的类相同.

PostQuote(后方法)

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//
                    }
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)

行情和主题(模型)

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; }
    }
Run Code Online (Sandbox Code Playgroud)

Ped*_*anz 53

正如您在本文本文中所看到的,您应该在创建StringContent时设置媒体类型

new StringContent(json, Encoding.UTF32, "application/json");
Run Code Online (Sandbox Code Playgroud)

  • 不知何故,它不适用于Encoding.UTF32.Encoding.UTF8确实有效.任何解释? (17认同)
  • 对我来说同样的问题,UTF8有效,UTF32没有. (6认同)
  • 如果您使用的是 C# / HttpClient,[此](https://gunnarpeipman.com/net/httpclient-remove-charset) 就是问题所在(与此处提到的其他问题完全无关)。 (3认同)

Rob*_*kes 7

我在处理快速而肮脏的反向代理时发现了这个问题。我需要表单数据而不是 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;
Run Code Online (Sandbox Code Playgroud)