【发布时间】:2019-06-30 00:34:12
【问题描述】:
即使我按如下方式添加了媒体格式化程序,我仍然收到此错误。我正在使用 postman 进行测试。 Postman 标头内容类型为 application/json,正文为 x-www-form-urlencoded。我该如何解决?
"ExceptionMessage": "没有 MediaTypeFormatter 可用于读取 来自媒体类型为'text/html'的内容的'Initiate'类型的对象。", “异常类型”:“System.Net.Http.UnsupportedMediaTypeException”
这是我的代码示例:
[RoutePrefix("api/v1/pin")]
public class GameController : ApiController
{
// POST: api/Game
[HttpPost, Route("initiation")]
public async System.Threading.Tasks.Task<Initiate> PurchaseInitiationAsync([FromBody]Initiate value)
{
if (value == null)
{
var message = new HttpResponseMessage(HttpStatusCode.NotFound)
{
Content = new StringContent(string.Format("Request is NULL! Please check your data.")),
ReasonPhrase = "Request is NULL! Please check your data."
};
throw new HttpResponseException(message);
}
HttpClient httpClient = new HttpClient();
HttpContent content = new StringContent(
JsonConvert.SerializeObject(value),
Encoding.UTF8,
"application/json"
);
HttpResponseMessage response =
await httpClient.PostAsync("http://test:1907/purchase_initiation", content);
var obj = response.Content.ReadAsAsync<Initiate>(
new List<MediaTypeFormatter>
{
new JsonMediaTypeFormatter()
}).Result;
return obj;
}
}
【问题讨论】:
-
这个问题并不重要,但是如果你在你的问题中粘贴一个例外,它通常是一个很好的做法来显示你得到它的行。
-
我认为在 WebApiCongif 中注册 JSONMediaTypeFormatter 可以解决这个问题。
config.Formatters.Add(new JsonMediaTypeFormatter()); -
没有没有用
标签: c# rest asp.net-web-api postman