首页 > 解决方案 > .net core restful api返回json,内容类型为application/json

问题描述

我想使用 .net 核心创建一个宁静的 api。该 api 将从 oracle db 中检索数据到数据表/数据集,然后返回 json 数据。但做不到。

如何使用 Content-Type: application/json 返回像结果 A 这样的有效 json?

    [HttpGet]
    // [Produces("application/json")] **** <---- return invalid JSON if this code is added
    public ActionResult Get()
    {   
        cmd = new OracleCommand(pQuery, _conn);
        oda = new OracleDataAdapter(cmd);

        DataTable dt = new DataTable();
        oda.Fill(dt);

        string jsonStr = JsonConvert.SerializeObject(dt, Formatting.Indented);
        return Ok(jsonStr);
    }

结果 A: Content-Type:text/plain [{ "id": 111, "name": "peter" },{ "id": 222, "name": "john" }]

结果 B: // [Produces("application/json")] **** <---- 如果添加此代码,它将返回 json,如下所示 Content-Type:application/json "[{\"id\": 111, \"姓名\": \"彼得\" },{ \"id\": 222, \"姓名\": \"约翰\" }]"

标签: jsonrest.net-core

解决方案


推荐阅读