WCF中的地址获取在实际编程中是一个比较重要的操作技术。我们今天为大家介绍的是有关这方面的一些基础知识,比如有关WCF寻址报头的一些应用技巧。希望可以给大家带来一些帮助。
在某些情况下,我们可能希望通过自定义寻址报头来解决一些复杂的问题,如根据根据传入的WCF寻址报头中是否包含某些信息,将其转发到不同的终结点,通过自定义寻址报头,可以实现SOAP消息的无限扩展,放置任何希望的控制信息到SOAP消息。如下面的代码:
- using (ServiceHost calculatorServiceHost =
- new ServiceHost(typeof(CalculatorService),
- new Uri("http://localhost:8887/CalculatorService")))
- {
- calculatorServiceHost.Opened += delegate
- {
- Console.WriteLine("Service begin to listen via the Address:{0}",
- calculatorServiceHost.BaseAddresses[0].ToString());
- };
- AddressHeader header =
- AddressHeader.CreateAddressHeader("basic",
- "http://www.cnblogs.com/terrylee", "Terrylee");
- EndpointAddress ea = new EndpointAddress(
- new Uri("http://localhost:8887/CalculatorService"), header);
- calculatorServiceHost.Description.Endpoints.Add(
- new ServiceEndpoint(
- ContractDescription.GetContract(typeof(ICalculator)),
- new WSHttpBinding(),
- ea));
- ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
- behavior.HttpGetEnabled = true;
- calculatorServiceHost.Description.Behaviors.Add(behavior);
- calculatorServiceHost.Open();
- Console.Read();
- }
我们在WSDL中可以看到该自定义的报头,它作为终结点引用的引用参数:
- < wsdl:service name="CalculatorService">
- < wsdl:port name="WSHttpBinding_ICalculator"
binding="tns:WSHttpBinding_ICalculator">- < soap12:address location="http://localhost:8887/CalculatorService" />
- < wsa10:EndpointReference>
- < wsa10:Address>http://localhost:8887/CalculatorService
< /wsa10:Address>- < wsa10:ReferenceParameters>
- < basic xmlns="http://www.cnblogs.com/terrylee">Terrylee< /basic>
- < /wsa10:ReferenceParameters>
- < Identity xmlns="http://schemas.xmlsoap.org/ws/2006/02/
addressingidentity">- < Upn>TerryLee-PC\TerryLee< /Upn>
- < /Identity>
- < /wsa10:EndpointReference>
- < /wsdl:port>
- < /wsdl:service>
截获到SOAP消息可以看到,在消息报头中添加了basic这样的信息,如下代码所示:
- < s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
- < s:Header>
- < basic xmlns="http://www.cnblogs.com/terrylee">Terrylee< /basic>
- < To s:mustUnderstand="1">http://localhost:8887/CalculatorService< /To>
- < Action s:mustUnderstand="1">http://tempuri.org/ICalculator/Add< /Action>
- < /s:Header>
- < s:Body>
- < Add xmlns="http://tempuri.org/">
- < x>1< /x>
- < y>2< /y>
- < /Add>
- < /s:Body>
- < /s:Envelope>
当然我们也可以通过配置的方式对WCF寻址进行自定义WCF寻址报头,如下代码所示:
- < service name="TerryLee.WCFAddressing.Service.CalculatorService"
- behaviorConfiguration="calculatorBehavior">
- < host>
- < baseAddresses>
- < add baseAddress="http://localhost:8887/Calculator"/>
- < /baseAddresses>
- < /host>
- < endpoint address=""
- binding ="wsHttpBinding"
- contract="TerryLee.WCFAddressing.Contract.ICalculator">
- < headers>
- < basic xmlns="http://www.cnblogs.com/terrylee">Terrylee< /basic>
- < /headers>
- < /endpoint>
- < /service>
WCF寻址报头的一些基本内容就为大家介绍到这里。
【编辑推荐】