c# - 从没有其属性的 web api 返回 JsonResult

标签 c# asp.net-mvc asp.net-mvc-4 asp.net-web-api json.net

我有一个 Web API Controller ,从那里我从一个操作返回一个对象作为 JSON。

我是这样做的:

public ActionResult GetAllNotificationSettings()
{
    var result = new List<ListItems>();
    // Filling the list with data here...

    // Then I return the list
    return new JsonResult { Data = result };
}

但是通过这种方式,包括其 Data 属性的 JsonResult 对象被序列化为 JSON。因此,该操作返回的最终 JSON 如下所示:

{
    "ContentEncoding": null,
    "ContentType": null,
    "Data": {
        "ListItems": [
            {
                "ListId": 2,
                "Name": "John Doe"
            },
            {
                "ListId": 3,
                "Name": "Jane Doe"
            },
        ]
    },
    "JsonRequestBehavior": 1,
    "MaxJsonLength": null,
    "RecursionLimit": null
}

我无法序列化此 JSON 字符串,因为 JsonResult 对象向其添加了各种其他属性。我只对 ListItems 感兴趣,没有别的。但它会自动添加如下内容:ContentTypeMaxJsonLength 等...

现在这对我不起作用,因为 JSON 字符串中的所有其他属性...

var myList = JsonConvert.DeserializeObject<List<ListItems>>(jsonString);

有没有办法从操作中发送一个 JSON 对象,这样它就不会添加我不需要的所有属性?

最佳答案

作为使用 ASP.NET API 大约 3 年的人,我建议改为返回 HttpResponseMessage。不要使用 ActionResult 或 IEnumerable!

ActionResult 不好,因为正如您所发现的。

Return IEnumerable<> 不好,因为您以后可能想扩展它并添加一些 header 等。

使用 JsonResult 不好,因为您应该允许您的服务可扩展并支持其他响应格式,以备将来使用;如果你真的想限制它,你可以使用 Action 属性来限制它,而不是在 Action 主体中。

public HttpResponseMessage GetAllNotificationSettings()
{
    var result = new List<ListItems>();
    // Filling the list with data here...

    // Then I return the list
    return Request.CreateResponse(HttpStatusCode.OK, result);
}

在我的测试中,我通常使用下面的辅助方法从 HttpResponseMessage 中提取我的对象:

 public class ResponseResultExtractor
    {
        public T Extract<T>(HttpResponseMessage response)
        {
            return response.Content.ReadAsAsync<T>().Result;
        }
    }

var actual = ResponseResultExtractor.Extract<List<ListItems>>(response);

通过这种方式,您实现了以下目标:

  • 您的 Action 还可以返回错误消息和状态代码,例如 404 not found,因此您可以通过上述方式轻松处理它。
  • 您的 Action 不仅限于 JSON,还支持 JSON,具体取决于客户端的请求首选项和 Formatter 中的设置。

看看这个:http://www.asp.net/web-api/overview/formats-and-model-binding/content-negotiation

关于c# - 从没有其属性的 web api 返回 JsonResult,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25408046/

相关文章:

html - 如何处理在 ASP.NET MVC 中返回文件的 Controller 结果

c# - System.Console 不包含的定义

c# - System.DllNotFoundException : 'Unable to load DLL ' libzkfp. dll': The specified module could not be found.(HRESULT 异常:0x8007007E)'

c# - SendMailAsync 导致 TaskCanceledException 的原因?

asp.net-mvc-4 - MVC4 中的日期时间格式 - DisplayTemplates

c# - 我应该将我的 C# 代码放在 MVC4 中的什么位置?

asp.net-mvc-4 - 在一个项目中混合 Web Api 和 ASP.Net MVC 页面

c# - 如果文件夹包含空格,如何处理文件路径中的空格?

c# - 我无法获得我在 Controller 中发布的文本框中的值

c# - 在 asp.net MVC 4 项目中使用 DataSet 作为数据模型