我可以在 WCF ServiceContract 中公开数据成员吗?

Can I expose a data member in a WCF ServiceContract?

在 WCF 服务中,是否可以在 ServiceContract 定义中包含数据成员?做这样的事情:

namespace My.Service.Contracts
{
    [ServiceContract]
    public interface IMyService
    {
        [OperationContract]
        ResultObject[] Search(SearchParams searchParams);

        [DataMember]
        MyCustomClass MyDataMember { get; }
    }
}

我可以从 ServiceContract 内部公开 MyDataMember 吗?场景将是这样的:下面的 class 实现了服务契约,其中包含我想使用 public field/property 公开的成员数据。看起来像这样的东西: 我正在尝试在实现服务合同的 class 中公开 field/property。例如:

public class MyService : IMyService
{
    private MyCustomClass _datafield;

    ResultObject[] Search(SearchParams searchParams){
        //Do the search
    }

    MyCustomClass MyDataMember {
      get: { return _dataField; }
    }
}

您不能继承 DataMember 属性。

定义为on msdn.

[AttributeUsageAttribute(AttributeTargets.Property|AttributeTargets.Field, Inherited = false,AllowMultiple = false)]
public sealed class DataMemberAttribute : Attribute

Although this does not technically restrict you to decorate interface members with DataMember attribute however you will have to decorate implementing classes members with this attribute too.

这不是预期的使用方式。

is it possible to include a data member inside a ServiceContract definition?

虽然编译器会很乐意让你"add"一个用[DataMember]装饰的属性到服务接口,任何WCF客户端都不会看到属性。

因此,如果您的服务接口定义为:

[ServiceContract]
public interface IMyService
{
    [OperationContract]
    ResultObject[] Search(SearchParams searchParams);

    [DataMember]
    MyCustomClass MyDataMember { get; }
}

...并假设您通过 添加服务引用 生成了客户端代理,您将看不到 MyDataMember:

请注意,在添加服务引用时您也不会看到任何属性。

向服务接口添加属性没有意义,添加[DataMember]也没有意义。您将 [DataMember] 添加到用 [DataContract] 装饰并在您的服务界面中引用的 class。

MSDN 对数据合同有这样的说法:

A data contract is a formal agreement between a service and a client that abstractly describes the data to be exchanged. That is, to communicate, the client and the service do not have to share the same types, only the same data contracts. A data contract precisely defines, for each parameter or return type, what data is serialized (turned into XML) to be exchanged. - Golly, tell me more...

WCF 本质上就是关于调用方法(实际上它更多的是关于创建统一通信 API 为您提供 RPC 作为免费的牛排刀)。通常通过向服务发送 SOAP 消息来调用方法(尽管它也可以是 REST)。消息具有用 [DataMember] 修饰的属性,以指示 属性 应该被序列化并包含在消息流中。还有[MessageContract],不过我们不去了。

无论如何,人们不会在 WCF 服务上访问 "a property",而是调用一个方法。

告诉我更多

要了解有关 epic-ness 即 WCF 的更多信息,为什么不查看下面的 link。底部甚至还有一个相当不错的例子: