发布Json对象时出现Asp.Net Wep Api 2错误

时间:2015-09-03 10:35:40

标签: asp.net json asp.net-web-api2

我使用ASP.NET Web API 2和EF6

开发3个简单的RESTFul服务

第一项服务的名称是ImageGallery,它从Database

返回ImageGallery json对象

我有两个这样的实体:

ImageGalley.cs:

public class ImageGallery
{
    [Key]
    public int ID { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Image> Images { get; set; }
}

此外,Image.cs:

public class Image
{
    [Key]
    public int ID { get; set; }
    public int ImageGalleryID { get; set; }
    public string Caption { get; set; }
    public string Url { get; set; }
    public virtual ImageGallery ImageGallery { get; set; }
}

我的控制器的获取方法:

    public IList<ImageGallery> GetImageGalleries()
    {
        var imgGalls = db.ImageGalleries.ToList();
        return imgGalls;
    }

对于帖子:

[ResponseType(typeof(ImageGallery))]
    public IHttpActionResult PostImageGallery(ImageGallery imageGallery)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        db.ImageGalleries.Add(imageGallery);
        db.SaveChanges();

        return CreatedAtRoute("DefaultApi", new { id = imageGallery.ID }, imageGallery);
    }

我已将这行代码放在我的Global.asax中以避免自引用循环:

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

我使用POSTMAN来获取和发布Json Objects。但是当我尝试发布时,我遇到了这个错误。

{
  "Message": "The request is invalid.",
  "ModelState": {
    "imageGallery": [
      "Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'MobileApis.Models.ImageGallery' because the type requires a JSON object (e.g. {\"name\":\"value\"}) to deserialize correctly.\r\nTo fix this error either change the JSON to a JSON object (e.g. {\"name\":\"value\"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.\r\nPath '', line 1, position 1."
    ]
  }
}

以下是我的GET回复:

    [
  {
    "Images": [
      {
        "ID": 3,
        "ImageGalleryID": 1,
        "Caption": "Image 1",
        "Url": "http://placehold.it/350x150"
      },
      {
        "ID": 4,
        "ImageGalleryID": 1,
        "Caption": "Image 2",
        "Url": "http://placehold.it/350x150"
      },
      {
        "ID": 5,
        "ImageGalleryID": 1,
        "Caption": "Image 3",
        "Url": "http://placehold.it/350x150"
      },
      {
        "ID": 6,
        "ImageGalleryID": 1,
        "Caption": "Image 4",
        "Url": "http://placehold.it/350x150"
      }
    ],
    "ID": 1,
    "Name": "Image Gallery 1"
  }
]

如果你帮助我,我会很高兴。

0 个答案:

没有答案