ASP.NET Web的API不序列化只读属性 [英] ASP.NET Web-API not serializing readonly property

查看:88
本文介绍了ASP.NET Web的API不序列化只读属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从迁移一个标准的MVC操作的API方法将新asp.net网站的API测试,突然一个只读属性不再序列化(均返回JSON)。这是预期的行为?

编辑:增加了code样品

我都Newtonsoft.Json 4.0.8和4.0 System.Json通过的NuGet包引用

 公开的IQueryable<汽车>获取()
        {
             返回_carRepository.GetCars();
        }        公共类车
        {
            公共IEnumerable的<照片及GT;相片
            {
                {返回_photos; }
            }            公共字符串previewImageUrl //不再连载
            {
                得到
                {
                     VAR mainImage = Photos.FirstOrDefault(O => o.IsMain preVIEW)Photos.FirstOrDefault();
                        返回mainImage!= NULL? mainImage.Url:(的String.Empty);
                    }
                }
             }
         }


解决方案

JsonMediaTypeFormatter 附带的测试使用了序列化不支持只读属性(自他们不会来回正确)。我们计划在解决这个在未来realese。

在平均时间,你可以使用自定义的JSON MediaTypeFormatter 实现,它使用Json.NET(有一个可用的here)代替内置的格式化。

更新:还检查了Henrik的有关挂接一个JSON.NET格式化博客:<一href=\"http://blogs.msdn.com/b/henrikn/archive/2012/02/18/using-json-net-with-asp-net-web-api.aspx\">http://blogs.msdn.com/b/henrikn/archive/2012/02/18/using-json-net-with-asp-net-web-api.aspx

I migrated an API method from a standard MVC action to the new asp.net Web-API beta and suddenly a read only property is no longer serialized (both returning JSON). Is this expected behaviour?

Edit: Added code sample

I have both Newtonsoft.Json 4.0.8 and System.Json 4.0 referenced through nuget packages

        public IQueryable<Car> Gets()
        {
             return _carRepository.GetCars();
        }

        public class Car
        {
            public IEnumerable<Photo> Photos
            {
                get { return _photos; }
            }

            public string PreviewImageUrl // No longer serialized
            {
                get
                {
                     var mainImage = Photos.FirstOrDefault(o => o.IsMainPreview) Photos.FirstOrDefault();
                        return mainImage != null ? mainImage.Url : (string.Empty);
                    }
                }
             }
         }

解决方案

The JsonMediaTypeFormatter that ships with the Beta uses a serializer that does not support read-only properties (since they would not round-trip correctly). We are planning on addressing this for the next realese.

In the mean-time you could use a custom JSON MediaTypeFormatter implementation that uses Json.NET (there's one available here) instead of the built-in formatter.

Update: Also check out Henrik's blog about hooking up a JSON.NET formatter: http://blogs.msdn.com/b/henrikn/archive/2012/02/18/using-json-net-with-asp-net-web-api.aspx

这篇关于ASP.NET Web的API不序列化只读属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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