【问题标题】:How to return a single DataRow object from Asp Web API?如何从 Asp Web API 返回单个 DataRow 对象?
【发布时间】:2017-01-08 21:15:30
【问题描述】:

所以我正在编写一些 Asp.Net WebApi 代码来与没有使用模型类的旧 C# 后端代码挂钩。 (从DataAccess返回的纯dataTable,疯了吧?我知道)

以下是我放在服务器端的代码。

 public IHttpActionResult GetProduct(int campaignID, int productID)
    {
        var so = new SearchOptions(campaignID)
        {
            ProductID = productID
        };

        var result = SearchManager.Search(so);
        if (result == null || result.Rows.Count == 0)
            return NotFound();
        return Ok(result.Rows[0]);

    }

我希望得到这样的回应:

{
Field1: "field1",
Field2: "field2",
...
}

但实际上我有这个:

{
  "rowError": "",
  "rowState": 2,
  "table": [
    {
      Field1 : "field1",
      Field2 : "field2",
      ...
    }
  ],
  "itemArray": ["field1","field2"],
  "hasErrors": false
}

我不想要所有这些rowErrorrowState...等

如果我在服务器端这样做:

public IHttpActionResult GetProduct(int campaignID, int productID)
        {
            var so = new SearchOptions(campaignID)
            {
                ProductID = productID
            };

            var result = SearchManager.Search(so);
            if (result == null || result.Rows.Count == 0)
                return NotFound();
            return Ok(result);

        }

我收到了这个:

[{Field1: "field1", Field2: "field2"..}]

这很遗憾被ngResource get 方法拒绝,因为它是一个数组而不是单个 Json 对象。

我该怎么办?如果我只想将单个 dataRow 作为 Json 字符串返回。

理想情况下,我想避免走上 Manoz 建议的创建响应对象的路径。 (不过感谢您的回答 Manoz)

谢谢

【问题讨论】:

    标签: c# asp.net json asp.net-web-api


    【解决方案1】:

    您可以使用 LINQ 将 DataRow 转换为 Dictionary

    public IHttpActionResult GetProduct(int campaignID, int productID)
    {
        var so = new SearchOptions(campaignID)
        {
            ProductID = productID
        };
    
        var result = SearchManager.Search(so);
        if (result == null || result.Rows.Count == 0)
            return NotFound();
    
        var row = result.Rows[0];
        return Ok(row.Table.Columns
            .Cast<DataColumn>()
            .ToDictionary(c => c.ColumnName, c => row[c]));
    }
    

    该操作根据需要返回 JSON:{ Field1: "field1", Field2: "field2", ... }

    【讨论】:

    • 像魅力一样工作。谢谢!
    【解决方案2】:

    你试过反序列化它吗?

    Using NewtonSoft.Json
    

    创建一个与您的响应匹配的单独类。我相信响应的格式将始终保持不变。

    public class Response{
        public List<response> table{ get;set; }
    }
    
    public class response {
        public string Field1 { get;set; }
        public string Field2 { get;set; }
    }
    

    现在使用 Newtonsoft.Json 反序列化响应

    var entities = SearchManager.Search(so);
    
    var result= JsonConvert.DeserializeObject<Response>(entities)
    var endResult= result.table[0] //will get you result
    

    帮助来源 - https://www.nuget.org/packages/newtonsoft.json/

    【讨论】:

    • 谢谢。但对不起,我会更新我的 OP。因为我试图避免为响应创建模型。
    • 那你为什么不能简单地查询-result.Rows[0].table[0]
    • 它再次返回给我一个数组。同Ok(result)
    • 不能相同。你在撒谎;D
    • 反正刚刚在这里尝试过 - jsonpath.com 查询等于 - result.Rows[0].table[0] ==> $.table[0] 看看你得到了什么。
    【解决方案3】:

    由于这只是几个月前发布的,假设您使用的是 API 2.x。此版本自动智能地处理返回格式,特别是无需实现显式 CAST。你只需要指定你想要的类型。例如在 AngularJS 中,这将告诉 API 你期望什么:

    $http({
      method: 'GET',
      responseType: 'json'
      url: ...
    }).then(function mySuccess(response){
      $scope.theRow = response.data;
    })
    

    在服务器 API 中,只需保留您的代码。在执行过程中,它会自动返回 JSON 格式的结果。

    【讨论】:

    • 再一次,根本不需要 CAST。
    猜你喜欢
    • 2020-02-05
    • 2016-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-10
    • 1970-01-01
    • 2017-04-13
    相关资源
    最近更新 更多