项目的服务端是个API,当客户端调用Post新增一条记录请求时遇到Unsupported Media Type.
var stringContent = new StringContent(JsonConvert.SerializeObject(PostResourceEntity)); HttpResponseMessage response = client.PostAsync("api/CallMe/", stringContent).Result;
详细异常信息如下:
给client加上各种可能的header后测试依然报错,仔细查看异常消息“request entity‘s media type...”, 难道是跟我Post过去的对象有关?
using (var client = new HttpClient()) { client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Add("Accept", "application/json"); client.DefaultRequestHeaders.Add("ContentType", "application/json"); client.BaseAddress = new Uri("http://localhost:65421/");
打断点调试
果真如此,解决方法:
stringContent.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/json");
搞定~