【问题标题】:WebApi Specify Content-Type as application/jsonWebApi 将 Content-Type 指定为 application/json
【发布时间】:2018-09-02 05:50:06
【问题描述】:

我正在尝试返回从第 3 方 API 检索到的 JSON 对象。

[Route("api/Catalog/Categories")]
public class CategoriesController : Controller
{
    //Get all categories
    [HttpGet]
    public IActionResult Get()
    {

        var client = new RestClient();
        client.BaseUrl = new Uri("http://api.tcgplayer.com");

        var request = new RestRequest(Method.GET);
        request.Resource = "/catalog/categories";
        request.RequestFormat = DataFormat.Json;
        request.AddHeader("Content-Type", "application/json; charset=utf-8");
        request.AddHeader("Authorization", "Bearer redacted");

        var tcgResponse = client.Execute(request);

        return Ok(tcgResponse.Content);
    }
}

内容类型显示为“文档”,这是不可取的。如何将内容类型指定为“application/json”?

我已经尝试添加了

[Produces("application/json")]

但这导致我的响应内容重复序列化。

【问题讨论】:

  • 为什么不返回 json(tcgResponse.Content)?此外,您可以反序列化内容并返回实体(方法的返回类型将是您的实体类型,而不是 IActionResult )
  • 我的想法是我需要 Web API 返回 JSON 对象,因此反序列化似乎是多余的。我可能是错的。
  • 对于返回类型,取决于API,分享一下tcgResponse.Content的截图,尝试使用邮递员请求/catalog/categories,分享给我们响应。您的图片是来自3rd party apiCategoriesController 的请求,您可以尝试检查内容。一般来说,它返回document 是一个plantext html。尝试用return Ok(new { Id = 1, Name = "Test" });替换return Ok(tcgResponse.Content);,你会得到预期的json吗?

标签: .net-core asp.net-core-webapi


【解决方案1】:

FTR 我最终对 return 语句进行了反序列化和重新序列化。不漂亮,但它有效。

 var tcgResponse = client.Execute(request);

 var r = JsonConvert.DeserializeObject<dynamic>(tcgResponse.Content);

 return r;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-26
    • 2012-07-11
    • 2016-02-25
    • 2012-05-22
    • 2022-01-01
    • 1970-01-01
    相关资源
    最近更新 更多