在网络中更改 json 结果 API

Changing the json result in web API

我在 visual studio 2015 年创建了一个 API。虽然 运行 API 它给了我预期的响应和数据。下面是我的控制器代码

public HttpResponseMessage GetByMsn(string msn, DateTime dt)
{          
    try
    {
        var before = dt.AddMinutes(-5);
        var after = dt.AddMinutes(5);

        var result = medEntitites.tj_xhqd
                     .Where(m =>
                     m.zdjh == msn &&
                     m.sjsj >= before &&
                     m.sjsj <= after).Select(m => new { MSN = m.zdjh, DateTime = m.sjsj, Signal_Strength = m.xhqd }).Distinct();


        return Request.CreateResponse(HttpStatusCode.Found, result);
    }
    catch (Exception ex)
    {
        return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
    }
}

WebApiConfig 文件在下面

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
config.Formatters.Remove(config.Formatters.XmlFormatter);
config.Routes.MapHttpRoute(
   name: "GetByMsn",
   routeTemplate: "api/{controller}/{action}/{msn}/{dt}",
   defaults: null,
   constraints: new { msn = @"^[0-9]+$" , dt = @"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$" }
   );

响应是

[
    {
        "MSN": "002999000077",
        "DateTime": "2017-10-11T10:16:51",
        "Signal_Strength": "17"
    },
    {
        "MSN": "002999000077",
        "DateTime": "2017-10-11T10:19:01",
        "Signal_Strength": "16"
    },
    {
        "MSN": "002999000077",
        "DateTime": "2017-10-11T10:20:57",
        "Signal_Strength": "16"
    },
    {
        "MSN": "002999000077",
        "DateTime": "2017-10-11T10:22:53",
        "Signal_Strength": "17"
    }
]

我想得到

{"list":
    [
    {
        "MSN": "002999000077",
        "DateTime": "2017-10-11T10:16:51",
        "Signal_Strength": "17"
    },
    {
        "MSN": "002999000077",
        "DateTime": "2017-10-11T10:19:01",
        "Signal_Strength": "16"
    },
    {
        "MSN": "002999000077",
        "DateTime": "2017-10-11T10:20:57",
        "Signal_Strength": "16"
    },
    {
        "MSN": "002999000077",
        "DateTime": "2017-10-11T10:22:53",
        "Signal_Strength": "17"
    }]
}

我只想在开头添加 list 名称。我是 API 的新手,所以我找不到路。

非常感谢任何帮助。

创建一个匿名对象,用您想要的 属性 包装您的结果。

return Request.CreateResponse(HttpStatusCode.Found, new {list = result});