FREE BOOK

Chapter 13 - Programmable Web

Posted by Addison Wesley Free Book | ASP.NET & Web Forms August 25, 2009
The new Web programming capabilities in WCF simplify the building of services for use on the Web. This chapter covers these services, including SOAP, POX, the UriTemplate class, the webHttpBinding binding, configuration-free hosting, and content syndication models.

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.

Listing 13.6 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.
Listing 13.6.
CustomerService

using System;
using System.ServiceModel;
using System.ServiceModel.Web;

namespace EssentialWCF
{
    [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
        }
    }
}

Total Pages : 9 34567

comments