ASP.NET MVC 4 ApiController 不序列化所有属性
我正在 asp.net mvc 4 beta 中测试新的 ApiController,但是当我尝试返回一个如下所示的类时,只有几个属性被序列化?
public class PageModel : IPageModel {
public string Id { get; set; }
public virtual IPageMetadata Metadata { get; private set; }
public PageModel() {
Metadata = new PageMetadata();
}
}
这是我的 api 控制器中的代码
// GET /api/pages/5
public PageModel Get(string id) {
return new PageModel { Id = "pages/1", Metadata = {Name = "Foo"} };
}
,这是结果
{
Id: "pages/1",
Parent: null
}
是否可以获得完整的对象,而不仅仅是一些东西?
I'm testing the new ApiController in asp.net mvc 4 beta but when I try to return an class that looks like the following only a few properties gets serialized?
public class PageModel : IPageModel {
public string Id { get; set; }
public virtual IPageMetadata Metadata { get; private set; }
public PageModel() {
Metadata = new PageMetadata();
}
}
this is the code in my api controller
// GET /api/pages/5
public PageModel Get(string id) {
return new PageModel { Id = "pages/1", Metadata = {Name = "Foo"} };
}
and this is the result
{
Id: "pages/1",
Parent: null
}
Is it possible to get the complete object and not only a few things?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只读属性未序列化。如果您希望序列化
Metadata
属性,请将其设置器设为公共。我认为这种行为对于输入参数来说是正常的,但对于输出来说却不是,这是你的情况。恕我直言,这是一个错误,可以通过使用支持此功能的 JSON 序列化器来解决,但也许他们会在最终版本之前修复它并允许将只读属性序列化为输出参数。实际上这并不是什么大问题,因为无论如何您都应该使用视图模型,因此只需将域模型映射到视图模型并让您的方法返回此视图模型,该视图模型将仅包含您实际需要向客户端公开的属性。该视图模型将包含具有公共 getter 和 setter 的属性。
Readonly properties are not serialized. Make the setter of the
Metadata
property public if you want it to be serialized. I think that this behavior is normal for input parameters but not for output which is your case. IMHO it's a bug that could be workarounded by using a JSON serializer which supports this but maybe they will fix it before the final release and allow readonly properties to be serialized for output parameters.Actually it's not a big pain, because you should be using view models anyway, so simply map your domain model to a view model and have your method return this view model which will contain only the properties that you need to actually expose to the client. This view model will contain properties with public getters and setters.