制作一个 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/