可以说我有类似的东西
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=2only 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.
更多推荐
发布评论