You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让ASP.NET Web API 2返回缩进格式化的垂直JSON数据?

问题:ASP.NET Web API 2返回XML包裹的JSON而非格式化JSON

我基于ASP.NET Web API 2开发Web接口,意图返回JSON格式数据,但在Google Chrome中显示为无缩进的紧凑水平格式,同时浏览器提示「此XML文件未关联任何样式信息」,实际返回内容是被XML的<string>标签包裹的JSON字符串,具体如下:

This XML file does not appear to have any style information associated with it. The document tree is shown below. 
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">[{"UserId":23,"Name":"Emily","Access":3,"Mobile":"07419231"},{"UserId":31,"Name":"Lydia","Access":5,"Mobile":"67567587"},{"UserId":45,"Name":"Peter","Access":1,"Mobile":"90345853"},{"UserId":56,"Name":"Lebron","Access":4,"Mobile":"43895449"},{"UserId":73,"Name":"Amber","Access":0,"Mobile":"45788477"}]</string>

我期望返回带缩进的垂直格式化JSON,格式示例如下:

[
    {
        "UserId":23,
        "Name":"Emily",
        "Access":3,
        "Mobile":"07419231"
    },
    {
        "UserId":31,
        "Name":"Lydia",
        "Access":5,
        "Mobile":"67567587"
    },
    {
        "UserId":45,
        "Name":"Peter",
        "Access":1,
        "Mobile":"90345853"
    },
    {
        "UserId":56,
        "Name":"Lebron",
        "Access":4,
        "Mobile":"43895449"
    },
    {
        "UserId":73,
        "Name":"Amber",
        "Access":0,
        "Mobile":"45788477"
    }
]

我的控制器代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Data;
using System.Data.SqlClient;
using Newtonsoft.Json;

namespace ApiTesting.Controllers
{
    public class TestController : ApiController
    {

        SqlConnection con = new SqlConnection(@"server=DESKTOP-US2AF5N; database=Test; integrated security=true;");

        public string Get()
        {
            SqlDataAdapter da = new SqlDataAdapter("Select * From TblDraft", con);
            DataTable dt = new DataTable();
            da.Fill(dt);
            if(dt.Rows.Count>0)
            {
                return JsonConvert.SerializeObject(dt);
            }
            else
            {
                return "No Data Found";
            }
        }
    }
}

解决方法

在webapi.config文件中添加以下代码后,问题已解决:

config.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;

内容的提问来源于stack exchange,提问作者user27429245

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 20:09:22