Chapter 4: WCF Binding (3)

Original text: http://www.wcftutorial.net/Introduction-to-WCF.aspx

Binding configuration

Configuration binding can be done through configuration files or program coding, let's see how two different ways are done Bar.

Administrative (configuration mode):

In the configuration file of the managed program, you can add the node <bindings> in the <system.serviceModel>, and add the specific binding type to the properties of the node. Properties for specific binding types are shown below. The bound name property will be used in the endpoint information.

<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:

In the following code, I create a WSHttpBinding object and assign the properties that need to be configured. This binding object will be added to the endpoint of the Service and used to communicate with the client. Similarly, you can create any kind of binding and add it to the endpoint.

//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();


Note: Configuring the binding properties in the configuration file is the best option, because when you deploy the service to production, there is no need to change the code and recompile. So using configuration files is good programming practice.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326751734&siteId=291194637