繁体   English   中英

发布AngularJS JSON数组ASP.NET Web API错误

[英]Posting AngularJS JSON Array ASP.NET Web API Error

这似乎是一个常见的问题,我已经研究和尝试了我今天在网上可以找到的所有内容,但我仍然无法继续工作。 使用带有chrome的开发人员工具,我能够查看请求有效负载,并且其中包含我要发布的数据,但随后出现错误

“无法将当前JSON数组(例如[1,2,3])反序列化为类型'CertAngular.cert_unit_Angular',因为该类型需要JSON对象(例如{“ name”:“ value”})才能正确地反序列化。要解决此问题错误或者将JSON更改为JSON对象(例如{“ name”:“ value”}),或者将反序列化类型更改为数组或实现了集合接口的类型(例如ICollection,IList),例如可以从中反序列化的List JSON数组。还可以将JsonArrayAttribute添加到类型中,以强制其从JSON数组反序列化。路径”,第1行,位置1。”

开发人员工具标头中包含的请求有效载荷为

[{“ cc_id”:7778,“ unit_id”:“ TEST1”,“ $$ hashKey”:“ object:5”}]

我已经尝试了所有我能找到的一切,使它能够正常工作,但我仍在努力。 我认为这是我忽略或不太了解的简单事情

在将一些数据添加到availableclients之后,AngularJS中HTTP帖子的代码就是这样完成的。

$scope.availableclients = [];


$scope.submitCertData = function () {

    var objdata = JSON.stringify($scope.availableclients);

    $http.post('api/PostAttempt2/Postcert_unit_Angular/', objdata)
    .success(function () {

        console.log("Posted");
    })

}

我正在将模板发布控制器用于“带动作的Web API 2控制器,使用Entity Framework”,其代码如下...(除了添加[FromBody]并尝试组合使用,我离开了Visual Studio如何创建它的代码)其他人建议的事情。)

// POST: api/PostAttempt2
[ResponseType(typeof(cert_unit_Angular))]
public IHttpActionResult Postcert_unit_Angular([FromBody]cert_unit_Angular cert_unit_Angular)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        db.cert_unit_Angular.Add(cert_unit_Angular);

        try
        {
            db.SaveChanges();
        }
        catch (DbUpdateException)
        {
            if (cert_unit_AngularExists(cert_unit_Angular.unit_id))
            {
                return Conflict();
            }
            else
            {
                throw;
            }
        }

        return CreatedAtRoute("DefaultApi", new { id = cert_unit_Angular.unit_id }, cert_unit_Angular);
    }

我的WebApi路由配置是...

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

        config.Routes.MapHttpRoute(
            name: "DefaultAPI",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }

感谢您的帮助,我可以提供所需的任何信息。 谢谢。

这是cert_unit_Angular类。 对不起,我错过了。

     public class cert_unit_Angular
    {
        public string unit_id { get; set; }
        public Int32 cc_id { get; set; }
    }

您的Web api期望使用此类{{unit_id“:” ncn“,” cc_id“:5}这样的东西,您需要的是它将是一个数组

所以定义这样的东西作为方法签名

public IHttpActionResult Postcert_unit_Angular([FromBody]List<cert_unit_Angular> unitID)

要么

public IHttpActionResult Postcert_unit_Angular([FromBody]cert_unit_Angular[] unitID)

暂无
暂无

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

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