绑定的配置
配置绑定可以通过配置文件或者程序编码的方式进行,让我们看看两种不同的方式是如何进行的吧。
Administrative (配置方式):
在托管程序的配置文件中,你可以在<system.serviceModel>中添加节点<bindings>,并且添加特定的绑定类型到该节点的属性中。特定绑定类型的属性如下所示。绑定的名称属性将会在终结点信息中使用。
<system.serviceModel> <services> <service name="MyService"> <endpoint address="http://localhost/IISHostedService/MyService.svc" binding="wsHttpBinding" bindingName="wshttpbind" contract="IMyService"> <identity> <dns value="localhost"/> </identity> </endpoint> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/> </service> </services> <bindings> <wsHttpBinding> <binding name="wshttpbind" allowCookies="true" closeTimeout="00:01:00" receiveTimeout="00:01:00" /> </wsHttpBinding> </bindings> </system.serviceModel>
Programming Model:
在下面的代码中,我创建了一个WSHttpBinding的对象,并且赋值了需要配置的属性。这个绑定对象将会添加到Service的终结点中,用来与客户端进行通信。相类似的,你可以创建任何种类的绑定,并且添加到终结点中。
//Create a URI to serve as the base address Uri httpUrl = new Uri("http://localhost:8090/MyService/SimpleCalculator"); //Create ServiceHost ServiceHost host = new ServiceHost(typeof(MyCalculatorService.SimpleCalculator), httpUrl); //Create Binding to add to end point WSHttpBinding wshttpbind = new WSHttpBinding(); wshttpbind.AllowCookies = true; wshttpbind.CloseTimeout = new TimeSpan(0, 1, 0); wshttpbind.ReceiveTimeout = new TimeSpan(0, 1, 0); //Add a service endpoint host.AddServiceEndpoint (typeof(MyCalculatorService.ISimpleCalculator), wshttpbind, ""); //Enable metadata exchange ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); smb.HttpGetEnabled = true; host.Description.Behaviors.Add(smb); //Start the Service host.Open(); Console.WriteLine("Service is host at " + DateTime.Now.ToString()); Console.WriteLine("Host is running... Press key to stop"); Console.ReadLine();
注意:将绑定的属性配置在配置文件中是个最好的选择,因为当你将服务部署到生产环境中的时候,不需要更改代码了并且重新编译。所以使用配置文件是好的编程实践。