WCF Learning Notes (rest rules-based approach)

Source: Internet
Author: User

First, the definition of WCF

WCF is the new technology introduced after. NET 3.0, which means a communication service based on the Windows platform.

First, before we learned about WCF, we also knew that he was actually an enhanced version of a service-oriented (SOA) framework technology.

If you are familiar with WebService, you will know that WebService is based on the XML+XSD,SOAP and WSDL three technologies , of course, he is also using the HTTP protocol communication, strictly speaking WebService is a service-oriented development standards. and the ASP. NET WebService is the service under the Microsoft platform.

WCF is, in part, an ASP. NET Web service because it supports industry standards and core protocols for Web service . officially, WCF it consolidates all of the technologies related to distributed systems under the. NET platform, such as Enterprise Sevices (COM +). NET Remoting, Web Service (ASMX), WSE3.0 and MSMQ Message Queuing. In the context of communication (communiation), it can span processes, across machines, across subnets, corporate networks and the Internet, and in the host program, you can host Asp.net,exe,wpf,windows forms,nt service,com+ (Host).

WCF can implement WebService functionality, meaning that WCF implements direct support for soap. Then WCF also supports rest protocol-based communication, which is strictly not a protocol, but defines several rules for accessing resources using the service. Rest-enabled Web services are simple services based on HTTP protocols and rest rules.

Rest rules are defined in 3 categories, 1. a service that can be accessed with a simple URI , 2. supports MIME type , 3. use a different HTTP method . MIME types are supported, and different data formats can be returned from the service, such as normal XML, JSON, and so on.

The rest rule is based on the four methods of the HTTP request: GET () Method--return data from service, POST () method--Create a new data source, PUT () Method--Update server, delete () method--Delete data resource.

Ii. WCF Project Instances

1) First we define the service contract , establish a class library project Service.interface, the link library to be referenced as follows:

Then we define a data contract class Employee.cs, note the wording of several specific features here, which also stipulates that he is a data contract class, the data contract class is the basic class that provides data support for other contracts.

Then is to create a service contract interface class IEmployeesService.cs, and SOAP-based service contract definitions are different, we do not need to apply the corresponding operation method above the OperationContractAttribute feature, but applied in the interface/ The ServiceContractAttribute attribute on a class is still required. The substitution of the OperationContractAttribute attribute here is WebGetAttribute and WebInvokeAttribute, which are defined in the System.ServiceModel.Web assembly.

2) Create a Homestay service, add a console program services

In the Console program service we define the following service type Employeesservice which implements the contract interface Iemployeesservice.

  Public classEmployeesservice:iemployeesservice {Private Staticilist<employee> list =NewList<employee>()        {            NewEmployee () {id="001", name="Zhang San", department=". NET Department", grade="1"},            NewEmployee () {id="002", name="John Doe", department="Java Department", grade="2"},            NewEmployee () {id="003", name="Harry", department="PHP Department", grade="3"},        };  PublicIenumerable<employee>GetAll () {returnlist; }         PublicEmployee Get (stringID) {Employee employee= list. FirstOrDefault (E = E.id = =ID); if(Employee = =NULL)            {                //prompt not found            }            returnemployee; }         Public voidCreate (Employee employee) {list.        ADD (employee); }         Public voidUpdate (Employee employee) { This. Delete (employee.            ID); List.        ADD (employee); }         Public voidDelete (stringID) {Employee employee= This.            Get (ID); if(Employee! =NULL) {list.            Remove (employee); }        }    }}

Next we host the Employeesservice service defined above in app. Config, which is the appropriate configuration. We added a unique endpoint to the hosted service and simply specified its ABC three elements. Unlike the endpoint we configured earlier, the binding type we used here is webhttpbinding.

<?xml version= "1.0" encoding= "Utf-8"?><configuration>  <startup>    <supportedruntime version= "v4.0" sku= ". netframework,version=v4.5 "/>  </startup>  <system.serviceModel>    <services>      <service name= "Service.employeesservice" >        <endpoint address= "Http://127.0.0.1:123/employees"        binding= "WebHttpBinding"          contract= "Service.Interface.IEmployeesService"/>      </service>    </services>  </system.serviceModel></configuration>

We will eventually host the service through the following procedure. We used to do service boarding using ServiceHost created based on the service type, where we are using ServiceHost its subclasses webservicehost

3) invocation of the service

Since our homestay service is entirely web-based, there is no essential difference from a normal web site. Because the getall and get operations of the Employeesservice service support Http-get requests, we can make requests in the browser for the address of the operation, and the returned data can be displayed directly on the browser. Shown is the result of invoking the GetAll operation (Http://127.0.0.1:123/employees/all) from the browser, and we can see that the list of all employees is returned as XML, Of course, the premise is to start the service program and then access the data in the browser:

Note: If your system is Win7, if you run the service program with an error that HTTP cannot register the URL process, you need to run the Visual Studio tool with administrator privileges.

We can also call the get operation through the browser and get the employee-based information in XML, directly by specifying the ID of the worker in the address (http://127.0.0.1:123/employees/001). The result of the serialization of an employee object with an official ID of 001 as shown.

We demonstrated how to use the Http-get to request an action address in a browser to render the returned result directly, and now we show how to make a service call using a service proxy created through channelfactory<tchannel>.

Create a new console program client:

To configure the App. Config file:

<?xml version= "1.0" encoding= "Utf-8"?><configuration>  <startup>    <supportedruntime version= "v4.0" sku= ". netframework,version=v4.5 "/>  </startup>  <system.serviceModel>    <behaviors>      <endpointBehaviors>        <behavior name= "Webbehavior" >          <webhttp/>        </behavior >      </endpointBehaviors>    </behaviors>    <client>      <endpoint name= " Service.employeesservice "     address=" http://127.0.0.1:123/employees "    behaviorconfiguration=" Webbehavior "     binding=" webhttpbinding "    contract=" Service.Interface.IEmployeesService "/>    </ Client>  </system.serviceModel></configuration>

As shown in the configuration fragment above, we define a client endpoint that matches the service retransmitting that has a WebHttpBehavior endpoint behavior applied to it. WebHttpBehavior can be said to be the core of the entire Web HTTP programming model, and most of the support for the Web is implemented through this behavior. The end point behavior is actually applied by the server endpoint through Webservicehost.

And finally the call:

static void Main (string[] args) {using (channelfactory<iemployeesservice> ChannelFactory = new Ch Annelfactory<iemployeesservice> ("Service.employeesservice")) {Iemployeesservice proxy = c                Hannelfactory.createchannel ();                Console.WriteLine ("All Employees list:"); Array.foreach<employee> (proxy. GetAll ().                ToArray (), employee = Console.WriteLine (employee));                Console.WriteLine ("\ n Add a new employee (004):"); Proxy.               Create (new Employee {Id = "004", Name = "Zhao Liu", Grade = "G9",                Department = "Administrative Department"}); Array.foreach<employee> (proxy. GetAll ().                ToArray (), employee = Console.WriteLine (employee));                Console.WriteLine ("\ n Modify employee (004) Information:"); Proxy. Update (new Employee {Id = "004", Name = "Zhao 62", Gr       Ade = "G11",             Department = "Sales Department"}); Array.foreach<employee> (proxy. GetAll ().                ToArray (), employee = Console.WriteLine (employee));                Console.WriteLine ("\ n Delete Employee (004) Information:"); Proxy.                Delete ("004"); Array.foreach<employee> (proxy. GetAll ().                ToArray (), employee = Console.WriteLine (employee));            Console.read (); }        }

  

From a programmatic point of view, we use exactly the same service invocation as the SOAP service, so how do we reflect the web-based nature of the service invocation? First, before we can access the GetAll and get two operations through the browser to prove that the two service operations are based on Http-get, the returned data is returned directly in simple XML, and is not encapsulated as soap. To prove that create, update, and delete are completely web-based, we can parse the contents of the HTTP request through fiddler.

WCF Learning Notes (rest rules-based approach)

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.