Join me to learn WCF (12) -- getting started with the Rest service in WCF, wcfrest

Source: Internet
Author: User
Tags webhost

Join me to learn WCF (12) -- getting started with the Rest service in WCF, wcfrest
I. Introduction

To use Rest with. NET Framework 3.0, you also need to build some components of the infrastructure. In. NET Framework 3.5, WCF added programming models and these infrastructure components in the System. ServiceModel. Web component.

The new programming model has two main new attributes: WebGetAttribute and WebInvokeAttribute. There is also a URI template mechanism to help you declare the URI and verb used for each method response .. NET Framework also provides a new binding (WebHttpBinding) and a new behavior (WebHttpBehavior). In addition, it also provides the WebServiceHost and WebServiceHostFactory classes to support the Rest service. Next, let's take a look at the current support and implementation of the Rest service in WCF.

Ii. What is the REST service?

Baidu has many answers to this question. Here is a detailed link in Baidu Encyclopedia: Rest service. In my understanding, the Rest service is: Previously we used to abstract the concept of a WCF Service as an operation, rest was first proposed by Roy Thomas Fielding in his doctoral thesis ("architecture style and network software system-based design. A Rest service abstracts a service as a resource. Each resource has a unique Uniform Resource Identifier (URI). We no longer use the call operation to interact with the service, it is implemented through the unified interface of HTTP standard verbs (GET, POST, PUT, and DELETE. In a word, the Rest service is a different way of thinking. It also acts as a resource and interacts with each other through HTTP verbs such as Get, Post, Put, and Delete. In this case, the question arises. What are the benefits of the Rest service? That is, why should we focus on Rest and implement it?

The advantage of Rest is that it is extremely simple to use, and the Rest service requires a small amount of coding work, which can reduce unnecessary work. The Rest Service has the following advantages:

  • No need to introduce the SOAP message transmission layer. lightweight and efficient HTTP formats can be directly applied.
  • It can be easily implemented in any programming language, especially in JS. The interaction between services using SOAP and JS is cumbersome, while the interaction between services using Rest and JS is very simple.
  • You can access the service without using any programming language, instead of using a Web browser.
  • Better performance and cache support. The Rest service can improve response time and user experience.
  • Scalability and stateless. The Rest service is based on the HTTP protocol, and each request is independent. Once called, the server does not retain any sessions. This makes it more responsive and provides service scalability by reducing the maintenance of the communication status.
Iii. Comparison of WXF and Asp.net Web APIs

WCF is a unified programming model provided by Microsoft to generate service-oriented applications. Asp.net Web API is a framework used to easily generate HTTP services that can be accessed by a wide range of clients, including browsers and mobile devices. Asp.net Web API is an ideal platform for generating Restful applications on. NET platforms. Now again, what is the difference between the Rest service and the SOAP service?

Rest is easier to use than SOAP services. For developers, the learning cost is low. As an old Web Service technology, SOAP has not been withdrawn from the historical stage in the near future, with the emergence of SOAP 1.2, some shortcomings of SOAP 1.1 have been improved.

Currently, REST is only based on HTTP and HTTPS Protocols, while SOAP supports any transmission protocol, including HTTP/HTTPS, TCP, SMTP, and other protocols. In addition to using XML as the data bearer, the Rest service also supports JSON, RSS, and ATOM formats.

The comparison between Rest and SOAP is as follows:

So under what circumstances does Rest and SOAP be used? This depends on the actual situation. The specific application scenarios are as follows:

  • Use SOAP for remote calls. If a service is provided as a function, the client calls the service to execute a function and uses SOAP. For example, a common requirement is authentication and authorization. Data Services use Rest.
  • SOAP should be used for non-functional requirements, such as security, transmission, and Protocol requirements.
  • When the bandwidth is low and the processing capability of the client is limited, you can consider using Rest. For example, consume services on a PDA or mobile phone.

After introducing the differences between Rest and SOAP, let's go back to the comparison between WCF and Asp.net Web APIs. For details, see the comparison between the two functions:

Using WCF, you can create reliable and secure Web services that can be accessed through various transmission methods. You can use ASP. NET Web APIs to create HTTP-based services that can be accessed from various clients. To create and design a new REST style service, use ASP. NET Web API. Although WCF provides some support for compiling the REST style service, ASP. the REST support in the NET Web API is more complete, and all future REST function improvements will be implemented in ASP.. NET Web API.

Iv. Implementing Rest services in WCF

The Rest service is also supported in WCF 3.5. It mainly provides WebHttpBinding to support Rest. Next we will use a specific instance to see how to implement a Rest service in WCF. We still follow the previous three steps to create the instance.

Step 1: Create a Rest service interface and implementation. The specific implementation code is as follows.

The Service Contract Code is as follows:

1 [ServiceContract (Namespace =" http://www.cnblogs.com/zhili/ ")] 2 public interface IEmployees 3 {4 // Contract operations are identified by the WebGetAttribute instead of the operation contract, this indicates that the service is a Rest Service 5 [WebGet (UriTemplate = "all")] 6 IEnumerable <Employee> GetAll (); 7 8 [WebGet (UriTemplate = "{id}")] 9 Employee Get (string id); 10 11 [WebInvoke (UriTemplate = "/", Method = "PUT")] 12 void Create (Employee employee); 13 14 [WebInvoke (UriTemplate = "/", Method = "POST")] 15 void Update (Employee employee ); 16 17 [WebInvoke (UriTemplate = "/", Method = "DELETE")] 18 void Delete (string id); 19} 20 21 [DataContract (Namespace =" http://www.cnblogs.com.zhili/ ")] 22 public class Employee23 {24 [DataMember] 25 public string Id {get; set;} 26 27 [DataMember] 28 public string Name {get; set ;} 29 30 [DataMember] 31 public string Department {get; set;} 32 33 [DataMember] 34 public string Grade {get; set;} 35 36 public override string ToString () 37 {38 return string. format ("ID: {0,-5} Name: {1,-5} Department: {2,-5} level: {3}", Id, Name, Department, grade); 39} 40}

The code above shows that the Rest service no longer uses the OperactionContract method to identify operations. In this case, each operation in the Rest architecture is treated as a resource, therefore, the operations here are identified by the WebGetAttribute feature and WebInvokeAttribute. The following describes the specific implementation of the contract, that is, the implementation code of the Rest service.

1 namespace WCFContractAndService 2 {3 public class EmployeesService: IEmployees 4 {5 private static IList <Employee> employees = new List <Employee> 6 {7 new Employee {Id = "0001 ", name = "LearningHard", Department = "Development Department", Grade = "G6"}, 8 new Employee {Id = "0002", Name = "James ", department = "QA", Grade = "G5"} 9}; 10 11 public Employee Get (string id) 12 {13 Employee employee Employee = employees. firstOrDe Fault (e => e. id = id); 14 if (null = employee) 15 {16 WebOperationContext. current. outgoingResponse. statusCode = System. net. httpStatusCode. notFound; 17} 18 return employee; 19} 20 21 public IEnumerable <Employee> GetAll () 22 {23 return employees; 24} 25 26 public void Create (Employee employee) 27 {28 employees. add (employee); 29} 30 31 32 public void Update (Employee emp) 33 {34 this. delete (emp. id); 35 employ Ees. Add (emp); 36} 37 38 public void Delete (string id) 39 {40 Employee employee = this. Get (id); 41 if (null! = Employee) 42 {43 employees. Remove (employee); 44} 45} 46} 47}

Step 2: implement the Rest service host. The console program is used as the host Program. The main implementation code is as follows:

Namespace RestServiceHost {class Program {static void Main (string [] args) {// The Rest Service uses the WebServiceHost class to provide the host using (WebServiceHost webHost = new WebServiceHost (typeof (EmployeesService) {webHost. opened + = delegate {Console. writeLine ("Rest Employee Service enabled successfully! ") ;}; WebHost. Open (); Console. Read ();}}}}

The corresponding configuration file is as follows:

<Configuration> <system. serviceModel> <services> <service name = "WCFContractAndService. EmployeesService"> <! -- Here the Rest service can only use WebHttpBinding as the binding --> <endpoint address = "http: // localhost: 9003/employeeService" binding = "webHttpBinding" contract = "RestContract. IEmployees "/> </service> </services> </system. serviceModel> </configuration>

Step 3: implement the Rest service to call the client. Here we create a proxy object through the channel factory. The specific implementation code is as follows:

1 namespace WCFClient 2 {3 class Program 4 {5 static void Main (string [] args) 6 {7 using (ChannelFactory <IEmployees> channelFactory = new ChannelFactory <IEmployees> ("employeeService") 8 {9 // create proxy class 10 IEmployees proxy = channelFactory. createChannel (); 11 12 Console. writeLine ("all employee information:"); 13 14 // perform operations on the Rest service through the proxy class 15 Array. forEach <Employee> (proxy. getAll (). toArray (), emp => Console. writeLine (emp. toString (); 16 17 Console. writeLine ("\ n Add a new employee {0003}:"); 18 proxy. create (new Employee19 {20 Id = "0003", Name = "", Department = "Finance Department", Grade = "G7" 21}); 22 23 Array. forEach <Employee> (proxy. getAll (). toArray (), emp => Console. writeLine (emp. toString (); 24 25 Console. writeLine ("\ n modify employee (0003) Information:"); 26 proxy. update (new Employee 27 {28 Id = "0003", Name = "", Department = "sales", Grade = "G8" 29}); 30 Array. forEach <Employee> (proxy. getAll (). toArray (), emp => Console. writeLine (emp. toString (); 31 Console. writeLine ("\ n Delete employee (0002) Information:"); 32 proxy. delete ("0002"); 33 Array. forEach <Employee> (proxy. getAll (). toArray (), emp => Console. writeLine (emp. toString (); 34 35 Console. read (); 36} 37} 38} 39}

The configuration file corresponding to the client is as follows:

<configuration>  <system.serviceModel>    <behaviors>      <endpointBehaviors>        <behavior name="webBehavior">          <webHttp/>        </behavior>      </endpointBehaviors>    </behaviors>    <client>      <endpoint name="employeeService" address="http://localhost:9003/employeeService"  binding="webHttpBinding" behaviorConfiguration="webBehavior"  contract="RestContract.IEmployees">              </endpoint>    </client>  </system.serviceModel></configuration>

After the above three steps, the Rest service construction is complete. Let's take a look at the running results of the program.

Run the service host Program as an administrator. The result is as follows:

All source code in this article: WCFRestService.zip

 

Related Article

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.