ASP.NET Web API 响应在浏览器和 Postman 中显示转义字符

问题描述 投票:0回答:2

我正在学习如何使用 ASP.NET 创建 Web API,但我在让 JSON 响应在浏览器中看起来不错时遇到问题。

将 JSON 字符串打印到调试控制台时,看起来不错:

{
  "a": 2,
  "b": "hello"
}

但是当在浏览器中或通过 Postman 查看它时(即使在“漂亮视图”中),我得到了这个:

"{\r\n  \"a\": 2,\r\n  \"b\": \"hello\"\r\n}"

我能让浏览器很好地显示结果吗?

这是我的测试模型:

namespace Test.REST.Models
{
    public class Test
    {
        public int a;
        public string b;

        public Test(int a, string b)
        {
            this.a = a;
            this.b = b;
        }
    }
}

这是我的测试控制器:

namespace Test.REST.Controllers
{
    public class TestController : ApiController
    {
        public string Get()
        {
            Test.REST.Models.Test test = new Test.REST.Models.Test(2, "hello");
            string json = JsonConvert.SerializeObject(test, Formatting.Indented);
            System.Diagnostics.Debug.WriteLine(json);
            return json;
        }
    }
}
c# asp.net rest escaping
2个回答
1
投票

你有一个错误,修复类

public class Test
{
    public int a { get; set; }
    public string b { get; set; }

    public Test(int a, string b)
    {
        this.a = a;
        this.b = b;
    }
}

修复后,我使用 VS 2019 和 Postman 测试了您的代码。一切看起来都很正常。

如果我使用

string json = JsonConvert.SerializeObject(test, Newtonsoft.Json.Formatting.Indented);

输出

{
  "a": 2,
  "b": "hello"
}

如果我使用 Chrome 浏览器,也会有同样的外观

删除 Newtonsoft.Json.Formatting.Indented 后

string json = JsonConvert.SerializeObject(test);

输出

{"a":2,"b":"hello"}

0
投票

使用 StringContent 类

public async Task<IHttpActionResult> Test()
{
    string json = JsonConvert.SerializeObject(yourObject);
    var Response = Request.CreateResponse(System.Net.HttpStatusCode.OK);
    Response.Content = new StringContent(json , Encoding.UTF8, "application/json");
    return ResponseMessage(Response);
}

或者更简单

return Json(yourObject); //don't serialize your object
© www.soinside.com 2019 - 2024. All rights reserved.