首页 > 解决方案 > 如何返回 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#restasp.net-web-apipostman

解决方案


api/v1/pin/initiation如果请求内容类型命中是,我只能重现这个text/html。您说您的 Postman 设置设置为application/json并且 body is x-www-form-urlencoded,但是根据我的测试,如果是这种情况,您上面显示的异常将不会被抛出。

我会通过打开 Postman 控制台 (CTRL+ALT+C) 并检查请求标头来仔细检查 Postman 是否确实发送了正确的内容类型标头。

在此处输入图像描述


推荐阅读