ASP。NET MVC4 Web API应用程序定义post方法来保存客户。 客户在POST请求体中以json格式传递。 post方法中的客户参数包含属性的空值。

如何解决这个问题,以便张贴的数据将作为客户对象传递?

如果可能的话,Content-Type: application/x-www-form-urlencoded应该使用,因为我不知道如何在javascript方法中更改它。

控制器:

public class CustomersController : ApiController {

  public object Post([FromBody] Customer customer)
        {
            return Request.CreateResponse(HttpStatusCode.OK,
            new
            {
                customer = customer
            });
        }
    }
}

public class Customer
    {
        public string company_name { get; set; }
        public string contact_name { get; set; }
     }

要求:

POST http://localhost:52216/api/customers HTTP/1.1
Accept: application/json, text/javascript, */*; q=0.01
X-Requested-With: XMLHttpRequest
Content-Type: application/x-www-form-urlencoded; charset=UTF-8

{"contact_name":"sdfsd","company_name":"ssssd"}

当前回答

使用JSON.stringify()来获取JSON格式的字符串,确保在进行AJAX调用时传递以下提到的属性:

contentType:“application / json”

下面是jquery代码让ajax post调用asp.net web api:

Var积= JSON.stringify ({ productGroup:“Fablet”, productId: 1、 productName:“Lumia 1525 64gb”, sellingPrice: 700 }); . ajax({美元 URL:“http://localhost/api/Products”, 类型:“文章”, contentType: application / json, 数据:产品, 成功:函数(数据,状态,xhr) { alert('成功! '); }, 错误:函数(xhr,状态,错误){ alert('更新错误发生- ' +错误); } });

其他回答

使用JSON.stringify()来获取JSON格式的字符串,确保在进行AJAX调用时传递以下提到的属性:

contentType:“application / json”

下面是jquery代码让ajax post调用asp.net web api:

Var积= JSON.stringify ({ productGroup:“Fablet”, productId: 1、 productName:“Lumia 1525 64gb”, sellingPrice: 700 }); . ajax({美元 URL:“http://localhost/api/Products”, 类型:“文章”, contentType: application / json, 数据:产品, 成功:函数(数据,状态,xhr) { alert('成功! '); }, 错误:函数(xhr,状态,错误){ alert('更新错误发生- ' +错误); } });

确保您的WebAPI服务期望一个强类型对象,其结构与您传递的JSON相匹配。确保你对要发布的JSON进行了stringify。

这是我的JavaScript(使用AngluarJS):

$scope.updateUserActivity = function (_objuserActivity) {
        $http
        ({
            method: 'post',
            url: 'your url here',
            headers: { 'Content-Type': 'application/json'},
            data: JSON.stringify(_objuserActivity)
        })
        .then(function (response)
        {
            alert("success");
        })
        .catch(function (response)
        {
            alert("failure");
        })
        .finally(function ()
        {
        });

这是我的WebAPI控制器:

[HttpPost]
[AcceptVerbs("POST")]
public string POSTMe([FromBody]Models.UserActivity _activity)
{
    return "hello";
}

1)在你的客户端,你可以给你发送http。在下面这样的字符串中提交请求

var IndexInfo = JSON.stringify(this.scope.IndexTree);
this.$http.post('../../../api/EvaluationProcess/InsertEvaluationProcessInputType', "'" + IndexInfo + "'" ).then((response: any) => {}

2)然后在你的web api控制器中你可以反序列化它

public ApiResponce InsertEvaluationProcessInputType([FromBody]string IndexInfo)
    {
var des = (ApiReceivedListOfObjects<TempDistributedIndex>)Newtonsoft.Json.JsonConvert.DeserializeObject(DecryptedProcessInfo, typeof(ApiReceivedListOfObjects<TempDistributedIndex>));}

3)你的ApiReceivedListOfObjects类应该如下所示

public class ApiReceivedListOfObjects<T>
    {
        public List<T> element { get; set; }

    }

4)确保你的序列化字符串(这里的IndexInfo)变得像下面的结构在JsonConvert。步骤2中的反序列化对象命令

var resp = @"
    {
        ""element"": [
        {
            ""A"": ""A Jones"",
            ""B"": ""500015763""
        },
        {
            ""A"": ""B Smith"",
            ""B"": ""504986213""
        },
        {
            ""A"": ""C Brown"",
            ""B"": ""509034361""
        }
        ]
    }";

下面的代码返回json格式的数据,而不是xml - web API 2

在全局中放入以下一行。asax文件

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
        GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);

我一直在研究这个问题,发现了一个相当奇怪的结果。假设在c#中你的类中有这样的公共属性:

public class Customer
{
    public string contact_name;
    public string company_name;
}

那么你必须处理JSON。按照Shyju的建议,stringify trick,并如下所示:

var customer = {contact_name :"Scott",company_name:"HP"};
$.ajax({
    type: "POST",
    data :JSON.stringify(customer),
    url: "api/Customer",
    contentType: "application/json"
});

然而,如果你在你的类上定义getter和setter,就像这样:

public class Customer
{
    public string contact_name { get; set; }
    public string company_name { get; set; }
}

然后你可以更简单地称呼它:

$.ajax({
    type: "POST",
    data :customer,
    url: "api/Customer"
});

这使用了HTTP报头:

Content-Type:application/x-www-form-urlencoded

我不太确定这里发生了什么,但它看起来像框架中的一个bug(功能?)假设不同的绑定方法调用不同的“适配器”,而application/json的适配器可以使用公共属性,而表单编码数据的适配器则不行。

不过,我不知道哪种做法才是最佳做法。