SOA - SOAP WCF camp vs. ROA - REST HTTP - ASP.NET Web API camp: Which one to choose?

SOA - SOAP – WCF camp vs. ROA - REST – HTTP - ASP.NET Web API camp: Which one to choose? Connected Systems: One of the biggest challenges / opportunit...
Author: Augustine Floyd
1 downloads 1 Views 541KB Size
SOA - SOAP – WCF camp vs. ROA - REST – HTTP - ASP.NET Web API camp: Which one to choose? Connected Systems: One of the biggest challenges / opportunities in the industry is the integration and reuse of the existing systems. Connectivity (Connect people, organizations, and existing systems) through connected applications becomes the key factor in the software development. Solution to this challenge lies on developing interoperable, loosely coupled, secure distributed application. Around a decade back, Web Services and other RPC style assist the developers to build distributed applications. The Windows Communication Foundation (WCF) simplifies development of connected applications through a new service-oriented managed programming model. WCF takes Web services to the next level by providing developers with a highly productive framework for building secure, reliable and interoperable applications that send messages between services and clients. WCF is pretty much mature now with .NET 4.5. At the same time, there is another camp/ community where started using REST (Representational State Transfer) which is another different, alternative architectural style for building resource oriented services. The REST architectural style was developed by W3C Technical Architecture Group in parallel with HTTP/1.1. The World Wide Web itself, based on HTTP, can be viewed as a REST-based architecture. . Unlike SOAP, Restful services simply relies on the HTTP application protocol verbs (GET – Fetch, PUT – Replace, POST – Insert and DELETE – Delete etc…). REST was initially described in the context of HTTP, but it is not restricted to HTTP protocol alone. RESTful architectures may be based on other Application Layer protocols, but in real time, it is only used with HTTP. At this moment, REST approach is gaining upper hand because of its simplicity and reach. Restful services won’t require any proxies to consume and it be reached by a variety of device and client platforms. Microsoft have seen the increase in emergence of Restful services exposed over plain HTTP rather than through a more formal RPC style (like SOAP or WS*). Microsoft already moved many of its implementations away from SOAP based technologies to REST. But WCF is not dead yet, it is still very well alive and in certain scenarios, it fit’s better than REST. Let’s discuss more around these two approaches and when, where to use.

SOAP vs. HTTP

Before going into WCF vs. Web API discussion, I would like to discuss more on some fundamentals. Any technology you mention which has its own merit and drawback. SOAP and HTTP protocols have different purpose and usage. Simple Object Access Protocol, is a communication protocol specification for exchanging structured information over HTTP. It is based on XML and platform, Language independent. It build on top of HTTP as an abstraction layer. From the past decade, everyone agrees that HTTP is the correct intended way for communication between applications over traditional remote procedure calls (RPC) between objects like DCOM and COBRA. SOAP is designed be versatile enough to allow multiple or any transport protocols including HTTP, SMTP, TCP, UDP, Named pipes or even JMS. One thing, I learned in the last few years in program management is any system which performs more than couple of intended functionality will eventually fail. SOAP actually was simple, but over time it tries to solve multiple enterprise demands like security, transaction, trust, discovery, federation etc. and slowly becomes complex and less interoperable. But if you want any of the WS-* specification feature, SOAP is the correct approach. For example: SOAP provides end-end message security compare to point to point communication. If the SOAP message is routed via multiple intermediaries before reaching the last receiver, the message itself is not protected once an intermediary reads it. Another example, say if you want a distributed transaction feature in your services, SOAP supports distributed transactions through the WS-Atomic Transaction (WS-AT) specification. Of course there are ways to achieve transaction in REST approach, but SOAP, WS-* make the implementation easy.

On the other hand, Hypertext Transfer Protocol (HTTP) is an application, communication protocol which is more than a simple transport protocol. HTTP itself provides most of the features like authentication, caching, and content-type negotiation, so why an additional abstraction layer or different protocol –

SOAP which is on top of HTTP anyway. In many scenarios, where you want to build services where the goal is reaching multiple devices, client platform, highly scalable, easy to consume, REST / HTTP services is the correct option. You can make REST / HTTP services secure, as similar to SOAP via HTTP authentication along with HTTPS. The key advantage with RESTful services are simpler and better reach. Is Web Popular?! ;) Web - WWW, which is omnipresent everywhere now. Almost everyone knows about Web. HTTP/RESTful Services simply follows the tenets of the web which provides the same reach to people. I will give you a specific example - Just think of accessing a Service as below. You can access whatever the book detail of any author you want through HTTP GET itself! No Soap Messages, Proxy etc. amazon.com/authors/{author}/{book} Ex: amazon.com/authors/ArunGanesh/VS2010 amazon.com/authors/{author}?book={book} Ex: amazon.com/authors/ArunGanesh?book=VS2010 HTTP provides the following nine methods or verbs that we can perform on an identified resource.        

HEAD – Similar to a GET request without the response body. This is useful for retrieving metainformation written in response headers. GET - Requests to just retrieve the specified resource. POST – Client sends data (message body) to the server for an action. PUT - Uploads or updates the resource. DELETE deletes the specified resource. TRACE - allows the client to see what is being received at the other end of the request chain and use that data for testing or diagnostic information OPTIONS Returns the HTTP methods that the server supports for specified URL. PATCH Is used to apply partial modifications to a resource.

1. In Web, every resource being referred by a unique identifier, also known as a universal resource identifier (URI). a. URL+URN = URI. URI / Segment of a URI map to Application Logic. In the above example you can see that the segment of the URL itself being mapped to an application logic. 2. Utilize HTTP Verbs - HTTP GET, POST, PUT, DELETE etc. 3. Utilize HTTP Headers for representing what content type is required and services is returning. For instance, you can represent things like: languages, authentication, authorization, accepted encoding, char set, content type, length etc...

WCF vs. ASP.NET Web API Windows Communication Foundation: The Microsoft Windows Communication Foundation is built on top of service -oriented design:    

Boundaries are explicit. Services are autonomous. Services share schema and contract, not class. Service compatibility is based on policy.

WCF takes Web services to the next level by providing developers with a highly productive framework for building secure, reliable and interoperable applications that send messages between services and clients. In Microsoft world, WCF is more mature and evolved a lot in the l ast few years. WCF is the Microsoft service-oriented communication infrastructure and programming platform and runtime system for building, configuring and deploying network-distributed services. WCF provides key characteristics like Transport Neutral (Http, TCP, MSMQ and Named Pipes), various security features, multiple messaging patterns (simplex, duplex and request reply), encodings (text, binary or MTOM), network topologies, and hosting models (Windows, Windows NT Service, Console and IIS). WCF Key Features   

Unification of existing .NET Framework communication technologies like ASMX, Remoting, Enterprise Services, WSE, MSMQ etc... Implementing latest Web Services Standards / WS* Specifications and to support interoperability, including reliability, security, and transactions. Implicit use of service-oriented development principles.

WCF delivers secure, reliable, transacted interoperability through built-in support for the WS-* specifications. For developers, this greatly reduces the amount of infrastructure code required to achieve interoperability along with other enterprise features. An application built on WCF can communicate with WCF-based applications running in a different process on the same Windows machine, WCF-based applications running on another Windows machine and applications built on other technologies, such as IBM WebSphere, BEA WebLogic, and other Web services built in J2EE that are standards compliant. These applications can be running on Windows machines or on machines running other operating systems, such as Sun Solaris, IBM z/OS, or Linux. WCF support various specifications/standards, including basic standards (XML, XSD, XPath, SOAP, WSDL) as well as advanced standards and specifications that comprise the WS-* architecture. These include: WSAddressing, WS- MetadataExchange, WS-Policy, WS-Security, WS-Trust, WS-SecureConversation, WSReliableMessaging, WS- AtomicTransaction, WS-Coordination, WS-Policy, and MTOM. WCF programs communicate through the exchange of messages.   

A message is a self-contained unit of data consists of header and a body. A message should contain one body and any number of headers. All Indigo messages are represented as XML, specifically SOAP envelopes containing XML Infosets.

There are three types of Messaging programs: Clients, Services and Intermediaries.   

Client program initiate and send the request message to Service program. Service program respond to the client message. The input message may cause the service to perform some action like code execution or reply back to the client with an output message. Intermediary is a program between Service and Client which do some tasks like routing, acting as gateway, monitoring etc…

WCF provides the following encodings:   

Text encoding, an interoperable encoding. Message Transmission Optimization Mechanism (MTOM) encoding, this is an interoperable way for efficiently sending unstructured binary data to and from a service. Binary encoding for efficient transfer.

One can have more encoding mechanisms like a compression encoding using the built-in extension points of WCF. WCF supports the following messaging patterns   

Simplex – One Way Messaging (Fire and Forget). Duplex – Asynchronous two-way messaging. (Ex: Remotely controlled robot). Request: Reply – Synchronous two-way messaging. (Ex: XML Web services)

Address: Where is the service? An address defines where messages can be sent. The format of an endpoint address depends on the transport mechanism.  

For instance, for HTTP Transport it looks like http://www.arunmvpblog.com:8080/services For TCP, it looks like net.tcp://www.arunmvpblog.com:9000/services

The endpoint address enables you to create unique endpoint addresses for each endpoint in a service. Binding: How do I communicate to the service? Binding provides information on how a service can be accessed including transport method (HTTP / HTTPS / TCP / Named pipe / MSMQ), encoding format (Text / Binary /MTOM), security mechanism, reliability requirement etc... A service to be accessible, at least it should be associate with either one or more bindings. A contract can support many bindings and a binding can support many contracts. Contract: What can the service do for me? A contract explains a service’s behavior, structures, or message formats. There are three types of contracts in Indigo Services including Service contracts, Data contracts and Message contracts. You define service contracts, data contracts, and message contracts by using declarative attributes. The class that needs to be exposed as a WCF service should be marked with ServiceContract attribute. Service contracts can be defined by annotating an interface with [ServiceContract]. Identify service operations by annotating methods with [OperationContract].

[ServiceContract] public interface IBook { [OperationContract] bool BookAvailable(string bookName, string authorName, int bookID) [OperationContract] bool AddCart(Book book) [OperationContract] void OrderBook(int bookID) } By default service contracts handle simple service calls. Data contract defines custom data structures like object or struct. If the service is using only simple types, there is no need to explicitly use data contracts. In Data Contracts, the data can be passed to and from services in XML Schema form. For instance, a data contract looks as follows: [DataContract] public class Book { [DataMember] public string bookName; [DataMember] public string authorName; ……… } Contrast to ASMX Web services, in WCF you need to decorate a class with Data contract attributes, to allow serialization. Data Contract specifies how the data is serialized and de -serialized. Indigo service exposes a service description (WSDL, WS-Policy) and one or more endpoints, with each endpoint exposing one or more service operations. An endpoint connects a contract and a binding with an address. At least one endpoint needs to be there to access that service. A service can have multiple endpoints. For instance,   

Endpoint1 = Address1 (http://www.arunmvpblog.com/WCF/) + Binding1 (Http / X.509 Cert / MTOM Encoding) + Contract1 (IContract1 interface) Endpoint 2 = Address 2 (net.tcp://www.arunmvpblog.com/WPF/) + Binding2 (TCP / Windows Security / Binary Encoding) + Contract2 (IContract2 interface) Endpoint 3 = Address3 (net.msmq://www.arunmvpblog.com/WF/) + Binding3 (MSMSQ / Binary Encoding) + Contract2 (IContract2 interface)

A service can have many endpoints (contract bound to address) coexisting and available at the same time. An endpoint consists of four properties:    

An address that specifies where the endpoint can be found. A binding that specifies how a client can communicate with the endpoint. The contract specifies what functionality the endpoint exposes to the client. A set of behaviors that specify local implementation details of the endpoint.

Why the move from WCF to ASP.NET Web API? Web Services (SOAP) to WCF (SOAP + WS-*) to WCF 3.5 (SOAP+ WS-* + HTTP request WebHttpBinding) to WCF REST Starter Kit (REST part of WCF) to WCF Web API to ASP.NET Web API (Moved away from WCF to ASP.NET MVC) As REST/ HTTP services start getting popular around .NET 3.5 time frame, Microsoft introduces features - WebHttpBinding part of WCF 3.5 and WCF REST Starter Kit to create RESTful services. The REST starter kit tries to enrich the support of WCF 3.5 for HTTP services.

WCF 4.0 and 4.5 introduces few other feature set along with WCF Web API and tries to simplify the development of HTTP / Restful services. Check this post http://arunmvp.blogspot.com/2011/07/whats-new-in-wcf-40.html on the .NET 4.0 features. But the key challenge is WCF is built on top of SOAP stack and treats HTTP as a transport instead of as an application

protocol. ASP.NET Web API is all about HTTP and moreover already one can start develop a service which can return JSON from an ASP.NET MVC controller. End of the day, ASP.NET provides a first class support for HTTP programming model and it make sense and easy for Microsoft to build Web API’s in ASP.NET MVC world rather than in WCF world.

ASP.NET Web API: ASP.NET Web API is a framework for building and consuming HTTP services. It’s latest Microsoft platform for building RESTful services. ASP.NET Web API takes the best features from WCF Web API and merges them with the best features from MVC! It supports the following features:               

Modern HTTP programming model Easily define your URI space using the flexibility of ASP.NET Routing Rich support for formats (JSON, XML, form URL encoded, OData, custom) and HTTP content negotiation Request validation using data annotations Automatically generate rich help page documentation for your web APIs Content negotiation and custom formatters Filters Code-based configuration Server-side query composition IIS hosting or Self-host Link generation Testability IoC integration Tracing VS template, scaffolding

Check out this article to get an idea around implementation is of ASP.NET Web API: http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api. You would have noticed how much it is integrated and part of ASP.NET MVC.

Final Conclusion: I see WCF/ SOAP and ASP.NET Web API/ HTTP as two separate service design options that you need to choose wisely based on your current scenario. Scenario Need to support specific scenarios like Message queues, duplex communication, end to end message security, distributed transactions, one way messaging etc…. Already you have existing working WCF services and would like to add HTTP support additionally. One code base to support both SOAP and RESTful endpoints Need to create a resource-oriented services over HTTP Your project is a MVC application and want to expose some functionality over HTTP Want to build only a HTTP / RESTful services Duplex communication over HTTP SQL backend and need to expose OData endpoints

WCF 4.5

ASP.NET Web API

It’s me!

It’s me! It’s me! It’s me! It’s me! It’s me! SignalR WCF Data Services