公开 WCF 服务可能无法直接使用的对象(数据契约)?

发布于 2024-07-17 04:45:31 字数 715 浏览 9 评论 0原文

我有一些使用继承的对象类。 看来我只能访问服务直接使用的对象。 让我向您展示我想要完成的任务:

[DataContract]
public class Object1
{
   [DataMember]
   int Id {get; set;}
}

[DataContract]
public class object2: Object1
{
   [DataMember]
   string Name {get; set;}
}

[DataContract]
public class object3 
{
    [DataMember]
    int SomeNumber {get; set;}
}

服务:

public int GetId(object2 obj)
{
    return GetTheId(object2.Name);
}

现在,由于我在服务中使用 object2,object1 也被序列化。 但是,出于某种原因,我可能希望公开 object3。 它可能是我必须传递的派生类,以便稍后可以为另一个进程确定其类型。 我没有看到这个对象被序列化。 我假设每当您设置 DataContract / DataMember 时,这些对象都会被序列化。 不暴露那些不开始使用的东西确实是有意义的,因为我可以看到暴露你可能不需要的东西的问题。 公开服务不直接使用的对象的最佳方法是什么? 谢谢

丹尼尔

I have some object classes that use inheritance. It seems that I can only get access to the objects that are directly used by a service. Let me show you what I am trying to accomplish:

[DataContract]
public class Object1
{
   [DataMember]
   int Id {get; set;}
}

[DataContract]
public class object2: Object1
{
   [DataMember]
   string Name {get; set;}
}

[DataContract]
public class object3 
{
    [DataMember]
    int SomeNumber {get; set;}
}

The Service:

public int GetId(object2 obj)
{
    return GetTheId(object2.Name);
}

Now since I am using object2 in the service, object1 gets serialized too. Howerver, I may want to have object3 exposed for some reason. It may be a derived class that I have to pass so that its type can be determined later for another process. I do not see this object getting serialized. I assumed that whenever you set the DataContract / DataMember those objects would get serialized. It does make sense not to expose something that is not begin used, becuase I can see an issue with exposing items you may not need. What is the best way to expose objects that are not directly used by a service? Thanks

Daniel

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

他是夢罘是命 2024-07-24 04:45:31

您应该使用 KnownType 属性

[DataContract]
[KnownType(typeof(object3))]
public class object2 
{
}

假设您的意思是 object3 是 object2 的子类:

public class object3: object2
{
}

You should decorate object2 (peculiar name for a class :)) with the KnownType attribute:

[DataContract]
[KnownType(typeof(object3))]
public class object2 
{
}

Assuming you mean object3 is a subclass of object2:

public class object3: object2
{
}
亚希 2024-07-24 04:45:31

我相信你已经回答了你自己的问题。 如果服务没有使用这些成员,那么您不应该公开它们。 公开服务所需的最小数据集总是更好,因为它通常会提高服务的可维护性。

I believe you answered your own question. If the members are not being used by the service, then you shouldn't be exposing them. It is always better to expose the minimal set of data required by the service, as it will generally increase maintainability of the service.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文