Create a wcfwebservice that supports both WSDL and rest

Source: Internet
Author: User
Tags soap wsdl

Create a wcfwebservice that supports both WSDL and rest

First, review the three basic concepts of REST,WCF and webservice.

Rest: The core concept of rest is "resources", and a URI represents a specific resource. One advantage of using it is that the client only needs to send a simple HTTP packet to operate the server's resources, without the complexity of the SOAP protocol package, which makes it easy to invoke rest services with JavaScript.

WCF: It's a development framework for distributed applications that integrates. NET platform and distributed systems, such as Enterprise Sevices (COM +). NET Remoting, Web Service (ASMX), WSE3.0, and MSMQ message queues.

WebService: It's the industry standard, the Web Service specification, and it's not a framework or technology. Microsoft's WebService framework is ASP.net WebService. It uses the SOAP protocol for data interaction, and it needs to provide a WSDL file to describe the WebService interface.

There are currently a number of development environments that provide support for WebService calls, such as In a vs.net environment, you only need to add a Web reference, you can generate a local and WebService proxy class, the local only need to use the proxy class to interact with the webservice, completely do not feel the existence of the SOAP protocol. However, if you want to use WebService in JavaScript, you'll have a bit of a trouble, because you need to encapsulate a SOAP XML packet. So is there a webservice that provides both a WSDL file for the development environment to generate a proxy class, and a simple JSON string that can be easily invoked in JavaScript? Of course, that's what this article needs to do.

1, in VS2010 to create a default Wcfservice project, the list of project documents are as follows.

This is a simple webservice. Now publish the WebService to IIS and the Wcfservice URL will be http://192.168.2.249:8084/Service1.svc after publication. Then a new WinForm program references the webservice and invokes the GetData method, as shown in the following figure

The next thing to do is to have the Wcfservice support the RESTful format for external service.

2. Add Aspnetcompatibilityrequirementsatribute declaration for Service1 Type

    [Aspnetcompatibilityrequirements (Requirementsmode = aspnetcompatibilityrequirementsmode.allowed)]
    public class Service1:iservice1
    {public
        
        string GetData (string value)
        {return
            string. Format ("you entered: {0}", value);
        }

        Public Compositetype getdatausingdatacontract (Compositetype composite)
        {
            if (composite = null)
            {
                throw new ArgumentNullException ("composite");
            }
            if (composite. Boolvalue)
            {
                composite. StringValue + = "Suffix";
            }
            Return composite
        }
    }

3, modify the IService1 interface, so that it supports the JSON format

    [ServiceContract]
    
    Public interface IService1
    {

        [OperationContract]
        [WebInvoke (method = ' get ', UriTemplate = ' Getdata/?value ={value} ",
            Requestformat = Webmessageformat.json, Responseformat = Webmessageformat.json)]//Use Json format request and reply
        String GetData (string value);

        [OperationContract]
        [WebInvoke (method = "POST", UriTemplate = "Getdatausingdatacontract",
            Requestformat = Webmessageformat.json, Responseformat = Webmessageformat.json)]//Use Json format to request and answer
        Compositetype getdatausingdatacontract (compositetype composite);

    }


4. Add a Global.asax file for Wcfservice and register a routing converter

    public class Global:System.Web.HttpApplication
    {

        protected void Application_Start (object sender, EventArgs e)
        {
            registerroutes ();
        }

        private void RegisterRoutes ()
        {
            //Edit The base address of Service1 by replacing the ' Service1 ' string below
            ROUTETABLE.ROUTES.ADD (New Serviceroute ("Service1", New Webservicehostfactory (), typeof (Service1));
        }
  
    


5, modify the Web.config file, add URL routing module, open the ASPNET compatibility mode and add a Standardendpoint node.

<?xml version= "1.0" encoding= "Utf-8"?> <configuration> <system.web> <compilation debug= "true" targetframework= "4.0"/> </system.web> <system.serviceModel> <behaviors> <servicebe haviors> <behavior> <servicemetadata httpgetenabled= "true"/> <servicedebug i Ncludeexceptiondetailinfaults= "false"/> </behavior> </serviceBehaviors> </behaviors&gt
    ; <servicehostingenvironment multiplesitebindingsenabled= "true" aspnetcompatibilityenabled= "true"/> <!--
        Open the ASPNET compatibility mode--> <!--Add a standardendpoints node--> <standardEndpoints> <webHttpEndpoint> <!--Configure the WCF REST service base address via the Global.asax.cs file and the default Endpoin T via the attributes on the <standardEndpoint> element below--> <standardendpoin T name= "" helpenabled= "true"Automaticformatselectionenabled= "true"/> </webHttpEndpoint> </standardEndpoints> </system.se Rvicemodel> <system.webServer> <!--add a URL to the routing module--> <modules runallmanagedmodulesforallrequests= "t Rue "> <add name=" urlroutingmodule "type=" System.Web.Routing.UrlRoutingModule, system.web, version=4.0.0.0, Cul Ture=neutral, publickeytoken=b03f5f7f11d50a3a "/> </modules> </system.webServer> </configuration& Gt


To this end, a webservice that supports both WSDL and restful has been completed.

The following are used to test soap calls and rest calls, respectively.

Test one: Call the WebService's getdatausingdatacontract in the new WinForm project

Interface (through the packet analysis, this invocation is using the method of soap, detailed analysis please refer to the previous article http://blog.csdn.net/zztfj/article/details/7012252).


Test two: Call the Getdatausingdatacontract interface of the webservice using a rest request in the Restclient client tool

Setting the Content-type to Text/json; When Charset=utf-8, the screenshot of the request and answer is as follows:

Setting the Content-type to Text/xml; When Charset=utf-8, the screenshot of the request and answer is as follows:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.