简体   繁体   English

$ http发布将值传递为null的Asp.Net Web API

[英]$http post passing value as null to Asp.Net Web API

I have a ASP.Net web API with one post method. 我有一个发布方法的ASP.Net Web API。 I'm calling the post method from angular js. 我从angular js调用post方法。 It is not passing me the data to API POST method, All my properties of my requestData object is null. 它没有将数据传递给API POST方法,我的requestData对象的所有属性均为null。 I'm not sure what is the mistake am doing here. 我不确定这是怎么回事。 Can anyone help me plz. 谁能帮我。

API Code API代码

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

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

Client Code 客户代码

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);
        });

Probably, your server side couldn't map your parameters correctly. 您的服务器端可能无法正确映射参数。 Data type matching is important while post some parameters. 发布某些参数时,数据类型匹配很重要。 You can change your client code like this: 您可以这样更改客户代码:

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

After doing as @Jaky71 says, you can learn how .net expects those objects by calling dummy methods with nulls or whatever you nees to mimic. 按照@ Jaky71的说明进行操作之后,您可以通过调用带有null或您需要模仿的东西的伪方法来了解.net如何期望这些对象。

.net has a strict parser .net有严格的解析器

You can use angular.toJson: 您可以使用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);
    });  

Also make sure that your properties match. 还要确保您的属性匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM