WCF技术剖析(卷1)WCF全面解析文摘

第1章 wcf简介

soa体现的是一种对关注点进行分解的思想,与技术无关

soa的基本思想:

a.服务自治  独立部署,不依赖其他

b.依赖于开放的标准  采用xml,xsd,及wsdl作为服务描述的“语言”

c.跨平台  java平台下的应用能够调用.net平台暴露出来的wcf服务

d.可组合的服务 原子服务,聚合型服务

e.服务的复用  场景无关性

f.松耦合  通过契约

-----------------------------------------------------------------------------------------------------

简单对象访问协议(SOAP)是一种轻量的、简单的、基于 XML 的协议,它被设计成在 WEB 上交换结构化的和固化的信息。 SOAP 可以和现存的许多因特网协议和格式结合使用,包括超文本传输协议( HTTP),简单邮件传输协议(SMTP),多用途网际邮件扩充协议(MIME)。它还支持从消息系统到远程过程调用(RPC)等大量的应用程序

WSDL

Web Services Description Language的缩写,是一个用来描述Web服务和说明如何与Web服务通信的XML语言
WS-*规范
 ------------------------------------------------------------------------------------------------------
com/dcom(组件)(远程调用),
.net remoting(不能跨平台),
web服务+wse,
msmq(支持离线,)
 

第2章 终结点地址与wcf寻址

终结点(ABC)

URI统一资源标识

http:超文本传输协议(80)/https(443):超文本传输协议,1.请求回复消息传输方式,2.无状态,3.无连接

net.tcp(808):传输控制协议,1.连接的(3次握手原则),2.有状态,3.支持全双工通信,4支持可靠通信   

net.pipe:命名管道,同一机器的跨进程通信

net.msmq:消息队列  1.公共消息队列 2.私有消息队列 private表示私有

-------------------------------------------------------------------

ServiceEndpoint,EndpointAddress,AddServiceEndpoint,

ClientBase<TChannel>,ChannelFactory<TChannel>,

地址报头,AddressHeader,

实例演示,通过地址报头进行授权(S201,S202,S203)

     <headers>
                  <sn xmlns="http://www.artech.com/">{DDA095DA-93CA-49EF-BE01-EF5B47179FD0}</sn>
                </headers>

[ServiceBehavior(AddressFilterMode = AddressFilterMode.Any)]

消息筛选策略(报头)(Exact,Prefix,Any)

精确匹配,基于前缀匹配,匹配任何地址

端口共享:

http.sys,专门用于http请求的监听(内核模式)

net.tcp ,port sharing service windows服务实现的(用户模式)

逻辑地址与物理地址:ListenUri,ListenUriMode (Explicit,Unique)

行为:服务行为,契约行为,终结点行为,操作行为

实例演示(通过tcpTarce进行消息的路由S205.206)

请求监听与消息分发:6种消息筛选器

第3章 绑定与信道栈

 信道栈:传输信道,消息编码信道,协议信道

实例演示(直接通过绑定进行消息通信 上s301)

CommunicationObject,

DefaultCommunicationTimeouts,

IChannel,

ChannelBase

mep消息交换模式:

1.请求回复,

2.数据报或者单工模式,one-way

3.双工模式,回调  a.请求过程中的回调 b.订阅-发布

状态保持的角度,信道分为  1.数据报信道,2.会话信道(保持一个客户端对象,具有相同的生命周期)

实例演示:(自定义信道s302)

信道监听器,(自定义信道监听器s302)

信道工厂,(自定义信道工厂s302)

绑定元素:(自定义绑定元素s302)

绑定:绑定元素的有序集合(自定义绑定s302,s303)

系统绑定:自定义绑定

NetTcpBinding,NetNamedPipeBinding和NetMsmqBinding,tcp,命名管道,消息队列

WSHttpBinding,WS2007HttpBinding实现跨平台

WSDualHttpBinding,实现基于http的双向通信

BasicHttpBinding

绑定配置:自定义绑定元素配置

第4章 服务契约

元数据与中间代码的关系和服务契约与服务实现的关系类似

wcf契约:1.对服务操作的描述:服务契约;2.对数据的描述:数据契约,消息契约,错误契约

------------------------------------------------------------------------------------------------

ServiceContractAttribute    (ServiceContract,接口或类,推荐以接口实现)

主要3个属性:

Name,(一个确定的名称)

Namespace,(公司名称或项目名称)

ConfigurationName,(对应配置文件中ending contract="")

其他属性:sessionmode(采用何种会话模式),HasProtectionLevel,ProtectionLevel(消息保护级别),CallbackContract(双向通信回调)

------------------------------------------------------------------------------------------------

OperationContractAttribute    (OperationContract,操作方法)

Name:(默认是操作方法名)   同一个契约中不能存在两个名称相同的操作

Action与ReplyAction:(消息交换模式和请求、回复消息的格式)

Action的2个主要作用:消息筛选和操作选择。

为终结点指定契约,在同一个服务契约下 Action是唯一的

未匹配消息处理器:Action='*',只能有一个

其他属性:AsyncPattern(异步模式),IsInitiating/IsTerminating(初始化,终结会话),IsOneWay(单向消息交换模式)

-----------------------------------------------------------------------------------------------

服务契约的继承,(操作可以继承)

契约描述:contractDescription,operationDescription,messageDescript

实例:通过messageDescript分析请求、回复消息结构

---------------------------------------------------------------------------------------------------

消息交换模式与服务操作:

1.请求回复模式(默认)

2.单向模式 (不允许有返回值)

3.双工模式

实例:通过双工通信实现回调(s403)

[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Reentrant)]

--------------------------------------------------------------------------------------------------

多线程与异步操作

1.异步信道调用

2.单向消息交换

3.异步服务实现:

a.通过beginxxx/endxxx进行异步服务调用

b.通过回调的方式进行异步调用

c.通过事件注册的方式进行异步服务调用  [OperationContract(AsyncPattern = true)]

----------------------------------------------------------------------------------------------

操作的选择与执行 dispatchoperation,clientoperation

第5章 序列化与数据契约

XmlSerializer

DataContractAttribute  DataContract,(只能用于枚举,类,结构体,不能用于接口)

DataMemberAttribute DataMember(字段和属性)

DataContractSerializer  MaxItemsInObjectGraph默认值65536

如何保持对象现有的引用结构 preserveReference = true

已知类型:不推荐在服务操作中以接口类型作为参数 knownTypeAttribute,serviceKnownTypeAttribute

泛型数据契约与集合数据契约:

数据契约集合:IEnumerable,Array,IList<T>,都定义成数组  字典数据契约

等效数据契约:数据成员的添加和删除,缺失的数据成员采用默认值 实现IExtensibleDataObject

数据契约代理:DataContract Surrogate

序列化在WCF框架中的实现:

消息格式化器,实例演示:通过自定义消息格式化器压缩信息(s521)

第6章 消息,消息契约与消息编码

wcf的应用领域:1.SOAP企业级应用  2.web应用rest服务

Message.CreateMessage

消息的基本操作:读,写,拷贝,关闭

消息报头和消息属性

实例演示(通过消息报头和消息属性实现上下文信息的传播s612)

消息契约:MessageContract

上传文件:将传输文件的内容流作为主体,将属性作为报头传递

消息编码器:MessageEncoder

第7章 服务寄宿

wcf的四大行为:服务行为,终结点行为,契约行为,操作行为

IIS与ASP.NET架构设计

Windows服务寄宿

第8章 客户端

服务代理

第9章 实例管理与会话

单调模式,单例模式,会话模式

第10章 REST服务

软件架构风格:SOAP,XML-RPC,REST(表征状态转移)

面向资源架构(ROA):一切数据都是资源,所有的资源均可被唯一标识,采用统一而简单的接口,基于表征的通信,无状态服务调用

 [ServiceContract]
    public interface IEmployees
    {
        [WebGet(UriTemplate = "all")]
        IEnumerable<Employee> GetAll();

        [WebGet(UriTemplate = "{id}")]
        Employee Get(string id);

        [WebInvoke(UriTemplate = "/", Method = "POST")]
        void Create(Employee employee);

        [WebInvoke(UriTemplate = "/", Method = "PUT")]
        void Update(Employee employee);

        [WebInvoke(UriTemplate = "{id}", Method = "DELETE")]
        void Delete(string id);
    }

 WebHttpBinding,WebGetAttribute,WebInvokeAttribute,WebHttpBehavior,WebServiceHost,WebServiceHostFactory,WebOperationContext,WebFaultException

URI模板,消息格式化,输出缓存与条件获取更新

第11章 wcf实例研究

下册

第1章 异常处理

servicedebugbehavior 应用于调试

  <behaviors>
      <serviceBehaviors>
        <behavior name="serviceDebuBehavior">
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  <service name="Artech.WcfServices.Service.CalculatorService" behaviorConfiguration="serviceDebuBehavior">
    

一般是自定义错误信息:

1.通过FaultException直接指定错误信息

   public class CalculatorService : ICalculator
    {
        public int Divide(int x, int y)
        {
            if (0 == y)
            {
                throw new FaultException("被除数y不能为零!");
            }
            return x / y;

        }
    }
  using (calculator as IDisposable)
                {
                   
try
                    {
                       
int result = calculator.Divide(1, 0);
                    }
                   
catch(FaultException ex)
                    {
                        Console.WriteLine(ex.Message);
                        (calculator
as ICommunicationObject).Abort();
                    }
                }

 2.通过FaultException<TDetail> 采用自定义类型封装错误

3.错误契约

2和3相结合,(S104)

  public interface ICalculator
    {
        [OperationContract]
        [FaultContract(typeof(CalculationError))]
        int Divide(int x, int y);
    }   
  [DataContract(Namespace = "http://www.artech.com/")]
    public class CalculationError
    {
        public CalculationError(string operation, string message)
        {
            this.Operation = operation;
            this.Message = message;
        }
        [DataMember]
        public string Operation { get; set; }
        [DataMember]
        public string Message { get; set; }
    }
  public class CalculatorService : ICalculator
    {
        public int Divide(int x, int y)
        {
            if (0 == y)
            {
                var error = new CalculationError("Divide", "被除数y不能为零!");
                throw new FaultException<CalculationError>(error, error.Message);
            }
            return x / y;
        }
    }
   try
                    {
                        int result = calculator.Divide(1, 0);
                    }
                    catch (FaultException<CalculationError> ex)
                    {
                        Console.WriteLine("运算错误");
                        Console.WriteLine("运算操作:{0}", ex.Detail.Operation);
                        Console.WriteLine("错误消息: {0}", ex.Detail.Message);
                        (calculator as ICommunicationObject).Abort();
                    }

第2章 元数据

1.XSD 2.WSDL 3.WS-Policy

第3章 事务

事务的特点:1.原子性 2.一致性 3.隔离性 4.持久性

1.SQL中的事务处理

2.ADO.NET事务控制

分布式事务:System.Transactions事务

TransactionScope事务

1.通过服务契约决定事务流转的策略

 [TransactionFlow(TransactionFlowOption.Allowed)]

2.通过绑定实施事务的流转

3.通过服务行为控制事务

实例演示:创建事务型服务(s301)

    using (TransactionScope transactionScope = new TransactionScope())
            {
                ServiceInvoker.Invoke<IWithdrawService>(proxy => proxy.Withdraw(fromAccountId, amount), "withdrawservice");
                ServiceInvoker.Invoke<IDepositService>(proxy => proxy.Deposit(toAccountId, amount), "depositservice");
                transactionScope.Complete();
            }

第4章 并发与限流

1.通过ServiceBehaviorAttribute特性定义并发模式

    // 摘要:
    //     指定服务类是支持单线程还是多线程操作模式。
    public enum ConcurrencyMode
    {
        // 摘要:
        //     服务实例是单线程的,且不接受可重入调用。如果 System.ServiceModel.ServiceBehaviorAttribute.InstanceContextMode
        //     属性为 System.ServiceModel.InstanceContextMode.Single,且其他消息在实例处理调用的同时到达,则这些消息必须等待,直到服务可用或消息超时为止。
        Single = 0,
        //
        // 摘要:
        //     服务实例是单线程的,且接受可重入调用。可重入服务接受在调用其他服务的同时进行调用;因此在调出之前,您需要负责让对象的状态一致,而在调出之后,必须确认本地操作数据有效。请注意,只有通过
        //     通道调用其他服务,才能解除服务实例锁定。在此情况下,已调用的服务可以通过回调重入第一个服务。如果第一个服务不可重入,则该调用顺序会导致死锁。有关详细信息,请参见
        //     System.ServiceModel.ServiceBehaviorAttribute.ConcurrencyMode。
        Reentrant = 1,
        //
        // 摘要:
        //     服务实例是多线程的。无同步保证。因为其他线程可以随时更改服务对象,所以必须始终处理同步与状态一致性。
        Multiple = 2,
    }

2.回调(callback)中的并发CallbackBehaviorAttribute

3.事务行为与并发 (默认模式是 并发模式single,才有效)

1.单调(percall)实例上下文模式

  [ServiceBehavior(UseSynchronizationContext = false,
                    InstanceContextMode = InstanceContextMode.PerCall)]
    public class CalculatorService : ICalculator
    {
        public double Add(double x, double y)
        {
            EventMonitor.Send(EventType.StartExecute);
            Thread.Sleep(5000);
            double result = x + y;
            EventMonitor.Send(EventType.EndExecute);
            return result;
        }
    }

相同客户端: (proxy as ICommunicationObject).Open();

2.会话(persession)实例上下文模式

3.单例(single)实例上下文模式

----------------------------------------------------------------------------------------

同步上下文与线程亲和性

synchronizationContext

流量限制:

1.通过编程的方式设置最大并发值

2.通过配置的方式设置最大并发值

第5章 可靠会话

  <reliableSession ordered="true"/>

第6章 队列服务

支持离线

第7章 传输安全

1.Transport安全模式

ssl,https  优缺点:高性能,点对点,适合intranet

2.Message安全模式

与协议无关,端对端,互操作性,跨平台

3.混合安全模式

---------------------------------------------------------------------------------

认证:

1.用户名、密码认证windows认证asp.net的成员资格membership,自定义逻辑认证

windows两种不同的认证协议:

1.NTLM:

2.kerberos:

2.数字证书认证

服务认证:

创建基于tls/ssl的服务:(s701)

<configuration>
  <system.serviceModel>
    <bindings>
      <netTcpBinding>
        <binding name="transportTcpBinding">
          <security mode="Transport">
            <transport clientCredentialType="None"/>
          </security>
        </binding>
      </netTcpBinding>
    </bindings>
    <services>
      <service     name="Artech.WcfServices.Service.CalculatorService"
                behaviorConfiguration="serviceCertificateBehavior">
        <endpoint    address="net.tcp://Jinnan-PC/calculatorservice"
                       binding="netTcpBinding"
                  bindingConfiguration="transportTcpBinding"
                  contract="Artech.WcfServices.Service.Interface.ICalculator" />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="serviceCertificateBehavior">
          <serviceCredentials>
            <serviceCertificate    storeLocation="LocalMachine"
                                storeName="My"
                                x509FindType="FindBySubjectName"
                                findValue="Jinnan-PC" />
          </serviceCredentials>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>
<configuration>
  <system.serviceModel>
    <bindings>
      <netTcpBinding>
        <binding name="transportTcpBinding">
          <security mode="Transport">
            <transport clientCredentialType="None"/>
          </security>
        </binding>
      </netTcpBinding>
    </bindings>
    <client>
      <endpoint     name="calculatorService"
                  address="net.tcp://jinnan-PC/calculatorservice"
                     binding="netTcpBinding"
                  bindingConfiguration="transportTcpBinding"
                  contract="Artech.WcfServices.Service.Interface.ICalculator"/>
    </client>
  </system.serviceModel>
</configuration>
  <serviceCertificate>
            <authentication certificateValidationMode="None"/>
          </serviceCertificate>

https自我寄宿:
https(iis/was寄宿):

客户端认证:

----------------------------------------------------------------------------------

消息保护:

安全会话:

第8章 授权与审核

第9章 扩展

第10章 wcf4.0新特性

原文地址:https://www.cnblogs.com/smileberry/p/3529232.html