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

制作一个 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");

https://stackoverflow.com/questions/31526558/

相关文章:

python - 如何以人类可读的格式序列化 Python 对象?

xml - CSV、JSON 和 XML 对于 REST API 的相对优点是什么?

ios - 将 iOS objective-c 对象转换为 JSON 字符串

c# - 模型绑定(bind)新的 Datatables 1.10 参数

jquery - 获取带有 AJAX 错误的服务器响应?

android - 如何调试我的改造 API 调用?

java - 如何使用 Jackson 注释从 HttpResponse 反序列化 JSON 对象?

java - 没有很多类的 GSON 解析

php - 如何在 symfony 中返回 json 编码格式错误

java - 如何使用 Java 和 Jackson 库对 Json 字符串进行多态反序列化?