c# - 如何返回 JSON 响应对象
问题描述
即使我按如下方式添加了媒体格式化程序,我也会收到此错误。我正在用postman测试。Postman 标头内容类型为 application/json,正文为 x-www-form-urlencoded。我该如何解决?
“ExceptionMessage”:“没有 MediaTypeFormatter 可用于从媒体类型为‘text/html’的内容中读取‘Initiate’类型的对象。”、“ExceptionType”:“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;
}
}
解决方案
推荐阅读
- c - 为什么我得到 0 而不是 C 中计算 x - y 和 x/y 的结果
- angular - 在 ngFor 期间并排显示当前和下一条记录
- python - 如何制作这个循环?
- javascript - JackBox- 响应式灯箱 - 图像查看器,使用 Javascript 函数而不是 href
- ruby - 文件在进程妖魔化时重新打开
- c++ - lambda 如何在 MSVC2017 15.9.3 和 /std:c++17 中使用静态局部错误返回值?
- jakarta-ee - 如何使用 Cachecontrol 和 etag 缓存列表对象?
- angular - 如何在 Angular 中获取响应式表单输入的值?
- android - ADAL 身份验证需要在 Android 上管理的设备
- javascript - javascript regex 查找后面替换字符