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

标签 c# .net json asp.net-web-api windows-phone

制作一个 windows phone 应用程序,虽然我可以轻松地从我的 Web 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//
                    }
                }
            }
        }

引用和主题(模型)

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

最佳答案

你应该在创建 StringContent 时设置媒体类型

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

关于c# - 发布到 Web API 时出现不支持的媒体类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31526558/

相关文章:

C# NET 服务器/客户端应用程序

c# - 在 ExecuteFunction SP 调用中使用 unicode 参数

java - Jersey 解析 JSON/Jackson 子类型反序列化的规则

javascript - 如何使用另一个 json 的顺序对 json 对象进行排序

c# - 如何在ElasticSearch中仅选择子对象的匹配字段?

c# - 如何使用访问 token 和刷新 token 从 google api 访问用户日历列表和事件

c# - 使用 .NET 和 Canvas 应用程序的 facebook api 获取 CanvasUrl 为空或为空

.net - 跨平台桌面 GUI 的首选开发平台?

json - 从编码结构 Golang 中删除转义字符

c# - 在方法中创建委托(delegate)类型