Web Api 2接收json数组 [英] Web Api 2 receive json array

查看:186
本文介绍了Web Api 2接收json数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

模型

public class modelVenta {
    public int idvendedor { get; set; }
    public int idcliente { get; set; }
    public int idproducto { get; set; }
    public int cantidad { get; set; }
    public decimal precio { get; set; }
    public DateTime fecha { get; set; }
}

public class modelVentas {
    public List<string> modeloVenta { get; set; }
}

控制器

[HttpPut]
[Route("api/ventas/Add")]
public HttpResponseMessage putVentas( List<modelVentas> data)
{
    return new HttpResponseMessage { StatusCode = HttpStatusCode.OK };
}

JSON

var data = [{
        "idvendedor": 1,
        "idcliente": 1,
        "idproducto": 1,
        "cantidad": 2,
        "precio": 12.0,
        "fecha": 1476445327124
    }, {
        "idvendedor": 1,
        "idcliente": 1,
        "idproducto": 2,
        "cantidad": 4,
        "precio": 23.0,
        "fecha": 1476445327124
    }, {
        "idvendedor": 1,
        "idcliente": 1,
        "idproducto": 1,
        "cantidad": 4,
        "precio": 35.0,
        "fecha": 1476445327124
    }];

发送数据

$http.put("http://localhost:54233/api/ventas/Add", JSON.stringify({
        modeloVenta: data
    })).then(function () {
        toastr.info('Elemento insertado correctamente');
    });

我在 http://jsonlint.com/中验证Json,并且可以,但是每次我从api控制器Web AngularJS始终接收Null. 请社区,有人可以帮助我解决这个问题吗?

I validate the Json in http://jsonlint.com/ and is ok, but every time I send from AngularJS, api controller web, always receives Null. please community, someone could help me solve this problem?

推荐答案

您的putVentas()方法期望使用List<modelVentas>-modelVentas仅具有List<string>属性.

Your putVentas() method is expecting a List<modelVentas> - With a modelVentas simply having a property of List<string>.

您要发送的JSON实际上是List<modelVenta>,DefaultModelBinder将尝试从接收到的JSON数据中将其反序列化为签名中指定的类型.

Your JSON that you're sending is actually a List<modelVenta>, which the DefaultModelBinder will try and deserialize to the type you've specified in the signature, from the JSON data it receives.

这就是为什么datanull的原因,因为它没有转换为方法签名期望的类型.

This is why data is null, as it doesn't translate to the type the method signature is expecting.

您的JSON试图将modelVenta列表传递给该方法.

Your JSON is trying to pass a list of modelVenta to the method.

要解决此问题,您将需要更新API方法以匹配JSON发送的类型.将API方法的签名更改为:

To fix this, you will need to update the API method to match the type that JSON is sending. Change your signature of the API method to be:

public HttpResponseMessage putVentas(List<modelVenta> data)
{
    // do something with the data

    return new HttpResponseMessage { StatusCode = HttpStatusCode.OK };
}

您的DefaultModelBinder应该知道您正在传递List<modelVenta>.

And your DefaultModelBinder should pick up that you're passing a List<modelVenta> instead.

这篇关于Web Api 2接收json数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆