【问题标题】:$http post passing value as null to Asp.Net Web API$http 将值作为 null 传递给 Asp.Net Web API
【发布时间】:2018-09-04 13:13:50
【问题描述】:

我有一个带有一种发布方法的 ASP.Net Web API。我正在从 Angular js 调用 post 方法。它没有将数据传递给 API POST 方法,我的 requestData 对象的所有属性都是空的。我不确定这里犯了什么错误。谁能帮帮我。

API 代码

public void Post(RequestData data)
{
.....
}

public class RequestData
{
    PropertyDetail propertyDetails;
    ICollection<Model1> model1s;
    ICollection<Model2> model2s;
    ICollection<Model3> model3;
    ICollection<Model4> model4;
}

客户代码

var requesData = new RequestData();
requesData.model0= $scope.model0;
requesData.model1s= $scope.models;
requesData.model2s= $scope.model2s;
requesData.model3s= $scope.model3s;
requesData.model4s= $scope.model4s;

        $http({
            method: 'POST',
            url: window.apiUrl,
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            data: requesData,
        }).then(function (res) {
            console.log('succes !', res.data);
            window.alert("Successfully created");
        }).catch(function (err) {
            debugger;
            console.log('error...', err);
        });

【问题讨论】:

  • 确保您从js 文件中收到的模型与.cs 文件中模型上每个property 的名称同步(目前不同)
  • 实际上我在这里用虚拟名称更改了我的实际属性名称 model0、model1 等,但代码中的名称是正确的。

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


【解决方案1】:

您的服务器端可能无法正确映射您的参数。发布一些参数时,数据类型匹配很重要。您可以像这样更改您的客户端代码:

...
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(requestData),
        dataType:'json',
...

【讨论】:

  • 实际上我注意到下面的行导致发布整个 html 页面。标头:{'Content-Type':'application/x-www-form-urlencoded'},如果我删除此标头,它会引发另一个错误“在严格模式下不允许访问函数的'参数'属性” .
【解决方案2】:

按照@Jaky71 所说,您可以通过调用带有空值或任何您需要模仿的虚拟方法来了解.net 如何期望这些对象。

.net 有一个严格的解析器

【讨论】:

  • 实际上我注意到下面的行导致发布整个 html 页面。标头:{'Content-Type':'application/x-www-form-urlencoded'},如果我删除此标头,它会引发另一个错误“在严格模式下不允许访问函数的'参数'属性”
  • 你不应该删除只是将其更改为 application/json
【解决方案3】:

你可以使用 angular.toJson:

$http({
        method: 'POST',
        url: window.apiUrl,
        headers: { 'Content-Type': 'application/json' },
        data: angular.toJson(requesData),
    }).then(function (res) {
        console.log('succes !', res.data);
        window.alert("Successfully created");
    }).catch(function (err) {
        debugger;
        console.log('error...', err);
    });  

还要确保您的属性匹配。

【讨论】:

    猜你喜欢
    • 2017-11-03
    • 2018-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多