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

30 篇文章 0 订阅
3 篇文章 0 订阅

/*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.


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


Add System.ServiceModel into reference.


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.


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


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


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


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


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.


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 :



IV. Consume WCF Web Service


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


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


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


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:



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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值