Friday 12 January 2018

Using WebGet and WebInvoke with example

Using WebGet and WebInvoke
Services can be exposed using the WebHttpBinding binding using either the WebGet or WebInvoke attributes. Each of these attributes specifies the HTTP verb, message format, and body style needed to expose an operation. We will examine each of these attributes and reasons to use each.

WebGet
The WebGet attribute exposes operations using the GET verb. The GET has significant advantages over other HTTP verbs. First, the endpoint is directly accessible via a Web browser by typing the URI to the service into the address bar. Parameters can be sent within the URI either as query string parameters or embedded in the URI. Second, clients and other downstream systems such as proxy servers can easily cache resources based on the cache policy for the service. Because of the caching capability, the WebGet attribute should be used only for retrieval.

WebInvoke
The WebInvoke attribute exposes services using other HTTP verbs such as POST, PUT, and DELETE. The default is to use POST, but it can be changed by setting the Method property of the attribute. These operations are meant to modify resources; therefore, the WebInvoke attribute is used to make modifications to resources.

Shows a service that defines services that are exposed in the WebGet and WebInvoke attributes. The WebGet attribute is used to retrieve customer information. The WebInvoke attribute is used for those operations that modify data such as adding or deleting customers. Last, the UriTemplate property is specified on WebGet and WebInvoke attribute to identify a customer resource using the URI.



  • using System;  
  • using System.ServiceModel;  
  • using System.ServiceModel.Web;  
  •   
  • namespace WCFExample  
  • {  
  •     [ServiceContract]  
  •     public class CustomerService  
  •     {  
  •         [OperationContract]  
  •         [WebGet(UriTemplate="/customer/{id}")]  
  •         public Customer GetCustomer(int id)  
  •         {  
  •             Customer customer = null;  
  •   
  •             // Get customer from database  
  •   
  •             return customer;  
  •         }  
  •   
  •         [OperationContract]  
  •         [WebInvoke(Method = "PUT", UriTemplate = "/customer/{id}")]  
  •         public void PutCustomer(int id, Customer customer)  
  •         {  
  •             // Put customer in database  
  •         }  
  •   
  •         [OperationContract]  
  •         [WebInvoke(Method = "DELETE", UriTemplate = "/customer/{id}")]  
  •         public void DeleteCustomer(int id)  
  •         {  
  •             // Put customer in database  
  •         }  
  •     }  
  • }  
  • No comments:

    Post a Comment