Share via


How to: Use netTcpBinding with Windows Authentication and Transport Security in WCF Calling from Windows Forms

patterns & practices Developer Center

Applies to

  • Microsoft Windows Communication Foundation (WCF) 3.5
  • Windows Forms
  • Microsoft Visual Studio 2008

Summary

This how-to article shows you how to use the netTcpBinding binding with Windows authentication and transport security. netTcpBinding is used for communicating with WCF clients in an intranet environment and provides transport security and Windows authentication by default. In this article, the WCF service is hosted in a Windows service.

Contents

  • Objectives
  • Overview
  • Summary of Steps
  • Step 1: Create a Windows Service
  • Step 2: Create a Sample WCF Service
  • Step 3: Modify the Windows Service to Host the WCF Service
  • Step 4: Configure the WCF Service to Use netTcpBinding with Transport Security
  • Step 5: Configure the WCF Service to Publish Metadata
  • Step 6: Install the Windows Service
  • Step 7: Create a Test Client Application
  • Step 8: Test the Client and WCF Service
  • Additional Resources

Objectives

  • Learn how to create a WCF service hosted in a Windows service.
  • Learn how to expose the WCF service over netTcpBinding to WCF-enabled clients.
  • Learn how to run the WCF service in the Network Service security context.
  • Learn how to call the service from a Windows Forms test client.

Overview

Windows authentication is well suited for scenarios in which your users have domain credentials. In the scenario described in this how-to article, users are authenticated by using Windows authentication. The scenario described in this how-to article uses the netTcpBinding binding to expose a WCF service to WCF-enabled clients. netTcpBinding offers improved performance over an HTTP binding. Because Internet Information Services (IIS) 6.0 cannot host a TCP binding, in this scenario WCF is hosted in a Windows service. The WCF service with netTcpBinding can be consumed by a WCF-enabled .NET application through the use of a service reference. The Visual Studio service reference generates a proxy class to abstract the underlying message-based communication. WCF transport security is used to support a secure communication channel in a point-to-point scenario. In general, you should always use transport security unless you need the additional flexibility that message security affords. For example, you would use message security for scenarios in which there are intermediaries that need to inspect and re-route the message.

In this how-to article, you will create a Windows service to host your WCF service. You will then create a sample WCF service in Visual Studio 2008 and configure the service to use netTcpBinding with transport security through the use of the WCF Configuration Editor. Next, you will configure mexTcpBinding so that the service can expose its metadata to clients, from which they can generate a WCF proxy and call your service. Finally, you will create a test client to verify that the service is working properly.

Solution Summary

  • Binding. By default, netTcpBinding offers improved performance over an HTTP binding and is the ideal choice for cross-machine communication between WCF clients and a WCF service, in an intranet environment.
  • Security mode. Transport security is the default security mode for netTcpBinding and should be preferred over message security for better performance. If needed, message security can provide greater control over signing and encryption of the message.
  • Client authentication. Because this binding is used within an intranet, Windows is the default and recommended client authentication mechanism. The other options for this binding are None (for anonymous authentication) and Certificate.
  • Protection level. It is recommended that you retain the default EncryptAndSign protection level for maximum transport security. This can be lowered to Sign for performance, but None is typically not recommended.
  • Hosting consideration. For the purposes of this How To article, WCF is hosted in a Windows service. In general, netTcpBinding services can be hosted in a Windows service, in Internet Information Services (IIS) 7.0 (not IIS 6.0 or lower), or in WAS, or it can be self-hosted. The choice should be based on the deployment requirements of the service.

Summary of Steps

  • Step 1: Create a Windows Service
  • Step 2: Create a Sample WCF Service
  • Step 3: Modify the Windows Service to Host the WCF Service
  • Step 4: Configure the WCF Service to Use netTcpBinding with Transport Security
  • Step 5: Configure the WCF Service to Publish Metadata
  • Step 6: Install the Windows Service
  • Step 7: Create a Test Client Application
  • Step 8: Test the Client and WCF Service

Step 1: Create a Windows Service

In this step, you create a Windows service to host your WCF service.

  1. In Visual Studio, on the File menu, click New > Project.

  2. In the New Project dialog box, in the Project Types section, select Windows under Visual C#.

  3. In the Templates section, select Windows Service, specify the project location, and name it “WCFServiceHost”.

  4. In the Add a Project dialog box, click OK to add a sample Windows service to the solution.

  5. Right-click Service1.cs and then click View Designer.

  6. Right-click the designer view and then click Add Installer to add the ProjectInstaller.cs file with two objects, serviceProcessInstaller1 and serviceInstaller1.

  7. In the designer view of ProjectInstaller.cs, right-click serviceProcessInstaller1 and then click Properties.

  8. In the properties section, set the Account attribute to NetworkService.

    This will run your Windows service under the Network Service account.

Step 2: Create a Sample WCF Service

In this step, you add a WCF service to the Windows service that will host it.

  1. Right-click the Widows Service project, click Add, and then click New Item.

  2. In the Add New Item dialog box, select WCF Service.

  3. Set the Name as MyService.cs and then click Add.

    Note that the configuration file, App.config, is automatically added.

  4. In IMyService.cs, modify the DoWork() method signature to accept a string parameter and return a string data type as follows:

    string DoWork(string value);
    
  5. In MyService.cs, modify the DoWork() method to accept a string parameter and return a string data type as follows:

    public string DoWork(string value)
          {
                return "Welcome " + value;
          }
    

Step 3: Modify the Windows Service to Host the WCF Service

In this step, you add code to the OnStart() and OnStop() methods to start and stop the WCF service inside the Windows service process.

  1. In the Solution Explorer, right-click Service1.cs and then click View Code.

  2. In the Service1.cs file, add a using statement as follows:

    using System.ServiceModel;
    
  3. Declare an internal static member of ServiceHost type as follows:

    internal static ServiceHost myServiceHost = null; 
    
  4. To open the service host, add code to the OnStart method of a Windows service as follows:

    protected override void OnStart(string[] args)
    {
       if (myServiceHost != null)
       {
           myServiceHost.Close();
       }
    
       myServiceHost = new ServiceHost(typeof(MyService));
       myServiceHost.Open();
    }
    
  5. To close the service host, add code to the OnStop method of a Windows service as follows:

    protected override void OnStop()
    {
       if (myServiceHost != null)
       {
          myServiceHost.Close();
          myServiceHost = null;
       }
    }
    
  6. Build the solution and verify that your project produces “WCFServicecHost.exe” in your project \bin directory.

Step 4: Configure the WCF Service to Use netTcpBinding with Transport Security

In this step, you configure your WCF service, “MyService”, to use netTcpBinding.

  1. Right-click the App.config file and then click Edit WCF Configuration.

    If you do not see the Edit WCF Configuration option, on the Tools menu, click WCF Service Configuration Editor. Close the WCF Service Configuration Editor tool that appears. The option should now appear on the web.config context menu.

  2. In the Configuration Editor, expand the Services node and then expand WCFHostService.MyService.

  3. Select the Host node, select the default BaseAddress from the Base addresses section, and then click Delete.

  4. In the Base Address Editor dialog box, click New, and then set the Base address: to "net.tcp://localhost:8523/WCFTestService".

    The port number 8523 is arbitrary and is used for this example only. WCFTestService is also arbitrary and is used in this example to expose the endpoint.

  5. Expand the Endpoints node, select the first [Empty Name] endpoint created, and then set the Name attribute to “NetTcpBindingEndpoint”.

  6. Set the Binding attribute to netTcpBinding by choosing this option from the drop-down list.

  7. In the Configuration Editor, on the File menu, click Save.

    Alternatively, press CTRL+S.

  8. In Visual Studio, verify your configuration in your App.config. The configuration should look as follows:

    <services>
        <service behaviorConfiguration="WCFHostService.MyServiceBehavior"
            name="WCFHostService.MyService">
            <endpoint address="" 
                      binding="netTcpBinding"
                      bindingConfiguration=""
                      name="NetTcpBindingEndpoint"
                      contract="WCFHostService.IMyService">
                <identity>
                    <dns value="localhost" />
                </identity>
            </endpoint>
    
            <endpoint address="mex" 
                      binding="mexHttpBinding"
                      contract="IMetadataExchange" />
            <host>
                <baseAddresses>
                    <add baseAddress="net.tcp://localhost:8523/WCFTestService" />
                </baseAddresses>
            </host>
        </service>
    </services>
    

    Note

    Because netTcpBinding supports Windows authentication with transport security by default, you do not have to change any other configuration in the binding.

Step 5: Configure the WCF Service to Publish Metadata

In this step, you configure your WCF service to publish metadata. Publishing the metadata will allow your client to add a reference to your WCF service.

  1. In the Configuration Editor, expand the Services node, and then expand the WCFHostService.MyService node.

  2. Expand the Endpoints node, select the second [Empty Name] endpoint created, and then set the Name attribute to MexTcpBindingEndpoint.

  3. Set the Binding attribute to mexTcpBinding by choosing this option from the drop-down list.

  4. In the Configuration Editor, on the File menu, click Save.

    Alternatively, press CTRL+S.

  5. In Visual Studio, verify your configuration in App.config. The configuration should look as follows:

    ...
    <services>
        <service behaviorConfiguration="WCFHostService.MyServiceBehavior"
            name="WCFHostService.MyService">
            <endpoint address="" 
                      binding="netTcpBinding" 
                      bindingConfiguration=""
                      name="NetTcpBindingEndpoint" 
                      contract="WCFHostService.IMyService">
                <identity>
                    <dns value="localhost" />
                </identity>
            </endpoint>
    
            <endpoint address="mex" 
                      binding="mexTcpBinding" 
                      bindingConfiguration=""
                      name="MexTcpBidingEndpoint" 
                      contract="IMetadataExchange" />
            <host>
                <baseAddresses>
                    <add baseAddress="net.tcp://localhost:8523/WCFTestService" />
                </baseAddresses>
            </host>
        </service>
    </services>
    ...
    
  6. In the Configuration Editor, expand the Advanced node, and then expand the Service Behaviors node.

  7. Expand the WCFHostService.MyServiceBehavior node and then select the serviceMetadata node.

  8. Set the httpGetEnabled attribute to False.

  9. In the Configuration Editor, on the File menu, click Save.

  10. In Visual Studio, verify your configuration in the App.config file. The configuration should look as follows:

    <behaviors>
        <serviceBehaviors>
            <behavior name="WCFHostService.MyServiceBehavior">
                <serviceMetadata httpGetEnabled="false" />
                <serviceDebug includeExceptionDetailInFaults="false" />
            </behavior>
        </serviceBehaviors>
    </behaviors>
    

Step 6: Install the Windows Service

In this step, you install the Windows service and run it from the Services console.

  1. Rebuild the solution and open a Visual Studio 2008 command prompt.

  2. Navigate to the \bin directory of the project where WCFServiceHost.exe was created.

  3. Execute the following command to install the service:

     > Installutil WCFServiceHost.exe
    
  4. If the service installs successfully, open the service console by typing services.msc in the Windows Run prompt.

  5. Search for the name of the service, Service1, and then start it.

Note

If you modified the service that is already installed, you can uninstall it by using following command:
> Installutil /u WCFServiceHost.exe

Step 7: Create a Test Client Application

In this step, you create a Windows Forms application named Test Client to test the WCF service.

  1. Right-click your solution, click Add, and then click New Project.
  2. In the Add New Project dialog box, in the Templates section, select Windows Forms Application.
  3. In the Name field, type Test Client and then click OK to create a Windows Forms application.
  4. Right-click your client project and then click Add Service Reference.
  5. In the Add Service Reference dialog box, set the Service URI: to net.tcp://localhost:8523/WCFTestService and then click Go.
  6. Change the Service reference name: to WCFTestService and then click OK.

Step 8: Test the Client and WCF Service

In this step, you use the test client to ensure that the WCF service is running properly.

  1. In your client project, drag a button control onto your form.

  2. Double-click the button control to show the underlying code.

  3. In the code behind the button click, create an instance of the proxy, and call the DoWork() method of your WCF service.

    When you call the service, your current user security context will automatically be passed to your WCF service. The code should look as follows:

    private void button1_Click(object sender, EventArgs e)
    {
          WCFTestService.MyServiceClient myService = 
             new WCFTestService.MyServiceClient();
          MessageBox.Show(myService.DoWork("Hello World!"));
          myService.Close();
    }
    
  4. Right click the client project and then click Set as Startup Project.

  5. Run the client application by pressing F5 or CTRL+F5.

    When you click the button on the form, the message “Welcome Hello World!” should appear.

Additional Resources