如何从Asp Web API返回单个DataRow对象

本文关键字:返回 单个 DataRow 对象 API Web Asp | 更新日期: 2023-09-27 18:04:58

所以我在写一些Asp。Net WebApi代码与没有使用模型类的旧c#后端代码挂钩。(从DataAccess返回的纯数据表,疯狂吧?我知道)

下面是我放在服务器端的代码:

 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
}

我不想要所有这些rowError, rowState…等等

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

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)

谢谢

如何从Asp Web API返回单个DataRow对象

您可以使用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", ... }

你试过反序列化吗?

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/

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

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

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