【问题标题】:Web api return null valueWeb api 返回空值
【发布时间】:2014-10-21 14:01:49
【问题描述】:

我有一个用于从服务器访问数据的 Web Api 控制器:

public class ServicesController : ApiController
{
    [AcceptVerbs("POST")]
    public IList<TreeMenuItem> LoadMetadata()
    {
        List<TreeMenuItem> itemsMenu = new List<TreeMenuItem>();
        TreeMenuItem dataSource = new TreeMenuItem("1", "DataSources", null);
        itemsMenu.Add(dataSource);
        return itemsMenu;
    }
}

由 angularJS 控制器调用:

angular.module('App').
controller('TreeMenuController', ["$scope", "$http", treeMenuController]);

function treeMenuController($scope, $http) {
var baseUrl = "api/Services/LoadMetadata";
$http.post(baseUrl)
    .then(function (result) {
        $scope.roleList = result.data;
    });

};

在浏览器网络中我有:

Request Method:POST
Status Code:200 OK
Request Headersview source
Accept:application/json, text/plain, */*
Accept-Encoding:gzip,deflate
Content-Length:2
Content-Type:application/json;charset=UTF-8

请求负载 {}

响应标头:

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Content-Length: 4

在响应选项卡中:[{}]。

怎么了?

【问题讨论】:

  • 您确定是result.data 而不仅仅是result
  • 我都试过了,看看响应选项卡表单网络浏览器:这是我得到的:{{}]
  • 您是否在 Web API 中设置了断点 - 它是否到达那里?您还有其他方法名称 LoadMetadata 吗?
  • 为什么不使用 [HttpPost] 而不是 AcceptVerbs。还有你为什么不使用[HttpGet]??
  • 正确执行LoadMetada方法

标签: json angularjs asp.net-web-api angular-http


【解决方案1】:

我让它工作: 最大的帮助是当我在浏览器中输入访问 api 服务的地址 (api/Services/LoadMetadata) 时的响应消息: 错误答案在一个 xml 文件中,我发现这是对象 TreeMenuItem 的序列化问题。建议是用 DataContract 类和 DataMember 类属性来装饰 - 就像在 WCF 中一样。在我这样做之后(需要在项目中添加对 System.Runtime.Serialization 的引用),一切都很完美。

【讨论】:

    猜你喜欢
    • 2019-02-13
    • 2018-07-09
    • 2018-10-18
    • 2018-11-06
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 2014-06-08
    • 1970-01-01
    相关资源
    最近更新 更多