简体   繁体   中英

How can I use SSL encryption in WCF

I have simple application from this tutorial: WCF 4 Getting Started Tutorial

How can I implement some encryption? Something like HTTPS (SSL?).

Example code from tutorial.

static void Main(string[] args)
    {

        // Step 1 of the address configuration procedure: Create a URI to serve as the base address.
        Uri baseAddress = new Uri("http://localhost:8000/ServiceModelSamples/Service");

        // Step 2 of the hosting procedure: Create ServiceHost
        ServiceHost selfHost = new ServiceHost(typeof(CalculatorService), baseAddress);

        try
        {


            // Step 3 of the hosting procedure: Add a service endpoint.
            selfHost.AddServiceEndpoint(
                typeof(ICalculator),
                new WSHttpBinding(),
                "CalculatorService");


            // Step 4 of the hosting procedure: Enable metadata exchange.
            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
            smb.HttpGetEnabled = true;
            selfHost.Description.Behaviors.Add(smb);

            // Step 5 of the hosting procedure: Start (and then stop) the service.
            selfHost.Open();
            Console.WriteLine("The service is ready.");
            Console.WriteLine("Press <ENTER> to terminate service.");
            Console.WriteLine();
            Console.ReadLine();

            // Close the ServiceHostBase to shutdown the service.
            selfHost.Close();
        }
        catch (CommunicationException ce)
        {
            Console.WriteLine("An exception occurred: {0}", ce.Message);
            selfHost.Abort();
        }

    }

The easiest way is probably to use transport security. See HTTP Transport Security . It describes how to configure SSL for both self-hosted and IIS-hosted services.

If all you need is encryption, then that's it. If you also want client authentication, then the client should use its own certificate which the service must accept.

If you want to have https in you IIS7 web site, you can try this:

  1. Change enabled protocol value "https" to your advance settings of the web site.
  2. Add bindings https port number eg: localhost:81
  3. Add SSL Settings to your web site.

Then access your site using http://fullyqnameofyourcomputer:81 If you want to access the WCF Service with basic binding with the secure site, just make sure you add securicty mode (Not None) in you client config.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM