.NET核心WebAPI在POST中很奇怪。没有正确序列化?

时间:2016-04-14 18:08:01

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

我有一个非常简单的帖子方法:

[HttpPost]
        public IActionResult Post(AgreementType model)
        {
            var ag = _facade.AddOrUpdateAgreement(model);
            return Json(ag);
        }

并试图对它发送一些测试调用,看它是否正常。它不是。我已经检查了浏览器中的网络选项卡以及fiddler,请求对我来说肯定是好的。 (Content-Type是application / json,身体就好了。)

我在服务器端post方法中放置了一个断点,它正在进入方法,模型结构正常,只是所有字符串都为空,数组为空。

这感觉就像是一个序列化问题,看起来我只是得到一个空的(新的)AgreementType模型而不是即将发布的模型......

编辑:这是json和C#模型:

json:

{
   "QuestionCategories": [1],
   "Id": 1,
   "Name": "Name",
   "ShortName": "Short Name"
 }

型号:

namespace DTModels.Models
{
   public class AgreementType
   {
       public virtual ICollection<QuestionCategory> QuestionCategories { get; set; }

       public AgreementType()
       {
           QuestionCategories = new HashSet<QuestionCategory>();
       }

       public int Id { get; set; }
       public string Name { get; set; }
       public string ShortName { get; set; }
   }
}

2 个答案:

答案 0 :(得分:2)

在你的c#对象中,QuestionCategories是QuestionCategory的集合,但在你的json中你发送了一个int集合。那不会映射。 YourJson需要像

{
   "QuestionCategories": [
                          {"prop1" : "value",
                           "prop2": "value"},
                          {"prop1": "value",
                           "prop2": "value"}
                         ],
   "Id": 1,
   "Name": "Name",
   "ShortName": "Short Name"
 }

其中prop1和prop2是QuestionCategory的属性,我的例子是在集合中传递2个对象。您还需要将标题中的内容类型设置为application / json。

答案 1 :(得分:0)

想出来。确保设置了内容长度!