【问题标题】:How to return JSON response object如何返回 JSON 响应对象
【发布时间】: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


【解决方案1】:

如果请求内容类型为api/v1/pin/initiationtext/html,我只能重现此内容。你说你的邮递员设置设置为application/json,正文设置为x-www-form-urlencoded,但根据我的测试,如果是这种情况,你上面显示的异常不会被抛出。

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

【讨论】:

  • 这里是邮递员控制台Request Headers: Content-Type:"application/x-www-form-urlencoded" cache-control:"no-cache" Postman-Token:"bbaa8370-bf3c-42a4-b10b-aff07b862885" User-Agent:"PostmanRuntime/7.6.0" Host:"localhost:61217" accept-encoding:"gzip, deflate" content-length:192
  • Response Headers: Cache-Control:"no-cache" Pragma:"no-cache" Content-Type:"application/json; charset=utf-8" Expires:"-1" Server:"Microsoft-IIS/10.0" X-AspNet-Version:"4.0.30319" X-SourceFiles:"=?UTF-8?B?QzpcVXNlcnNcMTk3MTk5XERvY3VtZW50c1xWaXN1YWwgU3R1ZGlvIDIwMTdcUHJvamVjdHNcRVBJTk1pZGRsZVdhcmVBUElcRVBJTk1pZGRsZVdhcmVBUElcYXBpXHYxXHBpblxpbml0aWF0aW9u?=" X-Powered-By:"ASP.NET" Date:"Wed, 06 Feb 2019 17:38:22 GMT" Content-Length:"2583
  • 好的,那么当您请求/api/v1/pin/initiation 时是否会引发此异常?您能否尝试通过返回硬编码的Initiate 来排除操作中的代码。如果这可行,则可能是您在 http://test:1907/purchase_initiation 调用的任何内容都引发了异常,并且该异常正在冒泡到您在 Postman 中看到的响应。
  • 我认为这是由于这个代码段HttpContent content = new StringContent( JsonConvert.SerializeObject(value), Encoding.UTF8, "application/json" ); 我可以看到正确的 JSON 数据是有价值的。有没有办法检查内容?
  • 所以你是说那行代码在原始问题中抛出了UnsupportedMediaTypeException?您是否附加了调试器并确认是这种情况?您是否按照我在上一条评论中的建议进行操作并检查如果您返回硬编码对象会发生什么?
猜你喜欢
  • 2016-12-07
  • 2017-04-05
  • 1970-01-01
  • 1970-01-01
  • 2021-09-10
  • 1970-01-01
  • 2014-06-02
  • 2018-02-08
  • 2013-08-22
相关资源
最近更新 更多