How to create, host, test and consume a WCF Web Service

/*by Jiangong SUN*/


WCF(Windows Communication Foundation) web service is used to facilitate the communication of different applications on different plateforms.
ASMX web service support HTTP protocol, while WCF web service support HTTP/HTTPS, TCP, IPC, MSMQ protocols.

Here we will discover together how to create, host and consume a WCF web service. Let's go!

I. Create a WCF web service

Firstly, we will create an empty solution.

How to create, host, test and consume a WCF Web Service_第1张图片

And then, we create a class library project named "HelloWorldService". Right click on this project and click "properties", name the namespace 
as "MyWCFServices".

How to create, host, test and consume a WCF Web Service_第2张图片

Add System.ServiceModel into reference.

How to create, host, test and consume a WCF Web Service_第3张图片

Add a new interface element and name it as "IHelloWorldService".
Modify the interface as following:

using System.Runtime.Serialization; //used for DataContract.
using System.ServiceModel; //used for ServiceContract. it contains the types necessary to build Windows Communication Foundation (WCF) service and client applications.

namespace MyWCFServices
{
    [ServiceContract]
    public interface IHelloWorldService
    {
        [OperationContract]
        string GetMessage(string name);

        [OperationContract]
        string GetPersonCompleteInfo(Person person);
    }

    //DataContract is used to be transmitted between web service and client
    [DataContract]
    public class Person
    {
        [DataMember]
        public int Age { get; set; }

        [DataMember]
        public string Sex { get; set; }

        [DataMember]
        public string Name { get; set; }
    }
}

Add a new class element named "HelloWorldService" and make it as following:

namespace MyWCFServices
{
    /// <summary>
    /// Create a service class and implement service interface
    /// </summary>
    public class HelloWorldService : IHelloWorldService
    {
        public string GetMessage(string name)
        {
            return "Hello world from " + name + "!";
        }

        public string GetPersonCompleteInfo(Person compInfo)
        {
            return "Person complete info( age is:" + compInfo.Age + ";sex is:" + compInfo.Sex + ";name is:" + compInfo.Name + ")";
        }
    }
}

Until now, the web service is created.


II. Host WCF Web Service


We'll create an empty asp.net web site "HostDevServer" for hosting web service.

How to create, host, test and consume a WCF Web Service_第4张图片

We add a reference of "HelloWorldService" in "HostDevServer".

How to create, host, test and consume a WCF Web Service_第5张图片

Configure a specific port "8080" and a virtual directory "/HostDevServer". In this way, we make the web service persistent.

How to create, host, test and consume a WCF Web Service_第6张图片

Press "Ctrl+F5", we can see the web site is running.

How to create, host, test and consume a WCF Web Service_第7张图片

Now we need to add a .svc file, because it will be used to host web service.

How to create, host, test and consume a WCF Web Service_第8张图片

Add hosting code in "HelloWorldService.svc":

<!--Host web service-->
<%@ServiceHost Service="MyWCFServices.HelloWorldService" %>

And then configure web.config file for hosting web service
The final result should be like this:

<?xml version="1.0" encoding="utf-8"?>

<!--
  Pour plus d'informations sur la configuration de votre application ASP.NET, consultez
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration><!--Root node of config file-->
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>

  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
  </system.webServer>
  
  <system.serviceModel><!--Top node of WCF Service-->
    <behaviors>
      <serviceBehaviors><!--Specify the bahaviors of a service-->
        <behavior name="MyServiceTypeBehaviors">
          <!-- httpGetEnabled Enable other programs locate the metadata of this web service, 
          client applications can't generate proxy and use web service without medatadata-->
          <serviceMetadata httpGetEnabled="true"/>

          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <services><!--List hosted WCF Services in this web site-->
      <!--Each service has its name, behavior and endpoint-->
      <service name="MyWCFServices.HelloWorldService" behaviorConfiguration="MyServiceTypeBehaviors">
        <!--wsHttpBinding means it's encrypted while transmitting data, while basicHttpBinding won't encrypt data-->
        <endpoint address="" binding="wsHttpBinding" contract="MyWCFServices.IHelloWorldService"/>
        <!--this endpoint is for metadata exchange-->
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
    </services>
  </system.serviceModel>
</configuration>

Set web site "HostDevServer" as startup project and press "Ctrl+F5" to run it.
Now we can see the web service is running.




III. Test WCF Web Service


We can use WCF test client to test our web service.

path for visual studio 2010: C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\WcfTestClient.exe

Run it and add "HelloWorldService" by its host address.

How to create, host, test and consume a WCF Web Service_第9张图片

We can test the two exposed methods. For example, i type Age equals 0, Name equals Charles and Sex equals Male. Then I call the service. 

It will generate the result like :

How to create, host, test and consume a WCF Web Service_第10张图片


IV. Consume WCF Web Service


Now we will create a console application "HelloWorld" to consume the web service.

How to create, host, test and consume a WCF Web Service_第11张图片

And then add "HelloWorldService" reference into project "HelloWorld".


Now we can see "HelloWorldService" is present in "Service References" folder.

How to create, host, test and consume a WCF Web Service_第12张图片

And the final code for "Program.cs" should be like this:

using System;
using HelloWorld.HelloWorldService; //add web service reference

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            //create an instance of web service client
            HelloWorldServiceClient hello = new HelloWorldServiceClient();
            //call GetMessage of web service
            Console.WriteLine(hello.GetMessage("charles"));
            //initialize an object with type person
            Person charles = new Person(){
                Age = 20,
                Sex = "male",
                Name = "charles"
            };
            //call GetPersonCompleteInfo of web service
            Console.WriteLine(hello.GetPersonCompleteInfo(charles));
            //close
            hello.Close();
        }
    }
}

Finally when we run the console application. It will show the result like this:

How to create, host, test and consume a WCF Web Service_第13张图片


This is the end and I hope this can do some help to you!

Enjoy coding!


reference: http://www.codeproject.com/Articles/97204/Implementing-a-Basic-Hello-World-WCF-Service

你可能感兴趣的:(Web,C#,C#,service,asp.net,asp.net,asp.net,asp.net,asp.net,WCF,WCF)