【问题标题】:$http get params is not received by apiapi 未收到 $http get params
【发布时间】:2017-05-22 17:03:33
【问题描述】:

我是 angularjs 和 webapi 的初学者。我在 angularjs 和 webapi 下创建了。我面临的问题是 api 对象只包含 null 而没有数据。谁能发现我做错了什么。

角度代码:

$scope.GetReport = function () {

    var ReportModel = {};
    debugger;
    var result = {};

    if (angular.isDefined($scope.Report.FromDate))
        ReportModel.FromDate = new Date($scope.Report.FromDate);
    else
        ReportModel.FromDate = null;
    if (angular.isDefined($scope.Report.ToDate))
        ReportModel.Todate = new Date($scope.Report.ToDate);
    else
        ReportModel.Todate = null;
    ReportModel.UserID = '';
    ReportModel.UserWWID = '1234';
    ReportModel.UserRole = '';
    ReportModel.ProjectType = '';
    ReportModel.ProjStatus = 'In Progress';
    ReportModel.CreatedBy = '11744439';
    ReportModel.LGroup = '';
    ReportModel.LUnit = '';
    ReportModel.LTeam = '';

    var config = {
        headers: { 'Content-Type': 'application/json;charset=utf-8' },
        datatype: JSON,
        data: JSON.stringify(ReportModel)
    };

    result = $http.get('api/Project/GetReport', { params: ReportModel })
                .then(function (response) {
                    result = response.data;
                    })
                }, function (response) {
                    alert('Failed ' + JSON.stringify(response.statusText));
                };
}

网络 API:

public IHttpActionResult GetReport(ViewReportModel objViewRepotModel)
    {
        try
        {
            //Code here
        }
        catch (Exception ex)
        {
            return NotFound();
        }
    }

【问题讨论】:

  • 你为什么不使用config object和post,比如$http.post('api/Project/GetReport', config)
  • 写问题时,尽可能少使用仍然会产生相同问题的代码。消除任何与问题无关的问题。

标签: angularjs asp.net-web-api


【解决方案1】:

$http 将 json 作为默认类型,因此您可以注释配置并将ReportModel 作为有效负载发送。

//var config = {
//    headers: { 'Content-Type': 'application/json;charset=utf-8' },
//   datatype: JSON,
//   data: JSON.stringify(ReportModel)
//};


var payload = {reportModel : ReportModel};
result = $http.post('api/Project/GetReport', payload)
            .then(function (response) {
                result = response.data;
                })
            }, function (response) {
                alert('Failed ' + JSON.stringify(response.statusText));
            };

此外,出于更好的安全原因,我建议您在此处使用$http.Post

【讨论】:

  • 我已经没有使用配置对象,如果我通过了你展示的方式,我什至看不到查询字符串中的参数
  • 您没有使用 web api 的基本路径,它应该类似于 http://localhostxxx/api/Project/GetReport
  • 另外,请参阅发送负载的变化。
猜你喜欢
  • 2021-02-22
  • 1970-01-01
  • 2018-11-22
  • 1970-01-01
  • 2019-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-30
相关资源
最近更新 更多