如何告诉asp.net mvc和api用私有setter反序列化模型?(How to tell asp.net mvc and api to deserialize model with privat

编程入门 行业动态 更新时间:2024-10-12 16:30:02
如何告诉asp.net mvc和api用私有setter反序列化模型?(How to tell asp.net mvc and api to deserialize model with private setter?)

可以说我有类似的东西

public class TestModel { public int a { get; set; } public int b { get; private set; } }

public ActionResult Test(TestMoel model) { .... }

然后导航到

/Test?a=1&b=2

只会设置属性a。 由于私人制定者,属性b被忽略。

有没有办法告诉序列化程序使用私有setter反序列化属性? (MVC和web api)

这样做有什么不利之处吗?

Lets say I got something like

public class TestModel { public int a { get; set; } public int b { get; private set; } }

and

public ActionResult Test(TestMoel model) { .... }

then navigate to

/Test?a=1&b=2

only property a will be set. property b is ignored due to private setter.

Is there a way to tell the serializer to deserialize properties with a private setter? (both MVC and web api)

Is there any downside for doing so?

最满意答案

虽然理论上可以编写一个利用反射映射到私有setter属性的自定义转换器,但不建议这样做。

相反,通过尊重属性访问者级别来保持清晰,一致的API边界是优先的。

实现这一目标的一种方法是利用不同的模型来实现不同的目标。 使用用作反序列化模型的所有公共setter创建一个简单的POCO。 使用在整个应用程序中使用的私有setter将该模型映射到第二个模型。 这使您可以在应用程序中实现正确的关注点分离。

While it is theoretically possible to write a custom converter that utilizes reflection to map to private setter properties, it is not recommended.

Rather, it is preferential to maintain clear, consistent API boundaries by respecting property accessor levels.

One way to achieve this is by utilizing different models to achieve different goals. Create a simple POCO with all public setters that is used as your deserialization model. Map that model to a second model with private setters that is used throughout your application. This allows you to achieve proper separation of concerns within your app.

更多推荐

本文发布于:2023-08-05 05:14:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1428149.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模型   序列化   api   asp   net

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!