ASP.NET

网站开发

契约

定义:描述服务功能的标准方式。

种类:

服务契约(Service Contract):客户能执行的操作。

数据契约(Data Contract):与服务交互的数据类型,可以是内建类型,如Int和String,也可以是自定义类型。

错误契约(Fault Contract):服务抛出的错误,以及处理和传输错误到客户端的方式。

消息契约(Message Contract):服务与消息交互。在具有专有消息格式的场景下适用,在大多数情况下,建议避免使用。

 

服务契约

用ServiceContractAttribute运行开发者定义一个服务契约,可以将ServiceContract标记到接口或类型上。

 

[ServiceContract]
interface IMyContract
{
  [OperationContract]
  
string MyMethod(string text);
  
string MyOtherMethod(string text);
}

class MyService : IMyContract
{
  
public string MyMethod(string text)
  {
    
return "Hello" + text;
  }

  
public string MyOtherMethod(string text)
  {
    
return "Cannot call this method over WCF";
  }
}

 注意:

1、WCF服务端的接口或类必须标记ServiceContract属性,才能供WCF客户端访问,包括内部接口,但其他类型都不允许。

2、需要在WCF契约中暴露的方法必须标记OperationContract属性才能成为契约的一部分。

3、WCF只允许OperationContract应用在方法上,而不允许应用到属性、索引器和事件上。WCF只能识别作为逻辑功能的操作。

 

应用ServiceContract特性

当接口应用了ServiceContract后,需要定义类实现该接口。

[ServiceContract]
interface IMyContract
{
   [OperationContract]
   
string MyMethod();
}

class MyService:IMyContract
{
   
public string MyMethod()
   {
      
return "Hello WCF";
   }
}

//显示实现接口
class MyService:IMyContract
{
   
string IMyContract.MyMethod()
   {
      
return "Hello WCF";
   }
}

//一个类实现多个服务接口,可以支持多个契约。
[ServiceContract]
interface IMyContract
{
   [OperationContract]
   
string MyMethod();
}

[ServiceContract]
interface IMyOtherContract
{
   [OperationContract]
   
void MyOtherMethod();
}

class MyService:IMyContract,IMyOtherContract
{
   
public string MyMethod(){...}
   
public void MyOtherMethod(){...}
}

 

posted on 2011-08-27 11:34  三千世界  阅读(237)  评论(0编辑  收藏  举报

导航