ASP.NET and WCF

Meet Your New Web Service: Moving from ASMX to WCF

15 Min Read
ITPro Today logo in a gray background | ITPro Today

ASP.NET Under the Hood

LANGUAGES:VB.NET | C#

ASP.NETVERSIONS: 2.0

 

ASP.NET and WCF

Meet Your New Web Service: Moving from ASMX to WCF

 

By Michele Leroux Bustamante

 

Q. Now that .NET 3.0 has been released, should I be usingWCF or ASMX Web services in my ASP.NET applications? Are ASMX and WSE obsolete?

 

A. Prior to the release of .NET 3.0 and WindowsCommunication Foundation (WCF), developers have been building Web services withASMX ASP.NET s answer to the Web service and Web Service Enhancements (WSE)to include interoperable protocols related to addressing, security, and largebinary attachments. Now, WCF is here a rich and complete platform fordistributed communication behind the firewall and for Web services using thelatest and greatest Web service standards. The question is, which technologyshould you use to build Web services going forward?

 

This is the first in a series of articles on WCF as thenew and improved Web service technology for ASP.NET developers. In this articleI ll discuss the evolution of Web service technologies and compare and contrastkey aspects of ASMX, WSE, and WCF. I ll discuss standard support, futureapplicability, and practicality of each platform. I ll also comment on thelearning curve from ASMX and WSE to WCF to prepare you for future installmentson this subject.

 

Evolution of Web Service Standards and Platforms

Introduced in 1999, SOAP and WSDL standards were shortspecifications that finally made it possible to describe a public endpoint, itsoperations, and the request and reply messages associated with each operationin such a way that it could be programmatically consumed to generate clientcode that invokes the endpoint. Before these specifications existed we had XMLschema to describe payloads sent to and returned from an endpoint butdevelopers had to find some means to communicate which endpoint to hit, andwhich schema were associated with those endpoints. Developers also had to writecustom code to generate or process XML (leveraging a parser, of course), and tosend HTTP GET and POST requests to the appropriate endpoint.

 

We ve come a long way since then, but it s amazing tothink about the simplicity of the early specifications (SOAP and WSDL). Bytheir simplicity, adoption was promoted Web service platforms appeared leftand right. Interoperability issues quickly surfaced, forcing platform vendorsto pay close attention to their XML parsers and SOAP engines to improveconsistency in how XML schema and WSDL were interpreted. In the meantime,standards building on SOAP and WSDL emerged to deal with addressing and routingscenarios, security, large binary attachments, reliable messaging,transactions, policy, and more. Like with SOAP and WSDL, these advancedstandards collectively labeled WS* cycle through phases of development andapproval, vendor adoption, and interoperability testing. A healthy collectionof these advanced standards have been fully ratified by W3C (http://www.w3c.org) and OASIS (http://www.oasis-open.org), while othersare still in the development or approval process.

 

In short, standards make Web services work; platformsimplement standards, and, as those implementations evolve, they reach aconsistency that promotes interoperability. For the ASP.NET platform, ASMX isthe Web service technology that implements the fundamental Web servicesupporting only SOAP and WSDL. Web Services Enhancements (WSE) version 1.0evolved to support very early implementations of non-ratified standards foraddressing, routing, security, and large binary attachments. WSE 2.0 was releasedfor the ASP.NET 1.x stack with implementations for the ratified addressing(WS-Addressing) and security (OASIS Web Service Security) standards and for thelatest state of non-ratified standards for security (WS-Trust,WS-SecureConversation) and for large binary attachments (DIME). WSE 3.0 was releasedfor the ASP.NET 2.0 stack with implementations MTOM, the ratified standardwhich makes DIME obsolete, and for further evolutions of advanced securitystandards. This is where it stops.

 

Enter the .NET Framework 3.0 and WCF. WCF is a platformthat incorporates all the latest and greatest WS* standards, ratified andnon-ratified, with the extensibility to evolve (like WSE) with the standards asthey are ratified and updated. WCF includes security, reliable messaging,transactions, and other standards that will never be supported by WSE. WSE wasalways intended to support transition to WCF.

 

As a side note, WCF is more than simply a Web serviceplatform. It is actually a platform for all forms of distributed communicationformerly achieved with .NET remoting, Enterprise Services and COM+, and Webservices. It unifies the developer experience so developers can learn a singleobject model to achieve all three results (I m focusing this article only onWCF as a Web service platform).

 

Architectural Similarities

Given that the standards are really what are behind a Webservice, and that the technology platform is merely a facilitator for thestandard, let s compare the architecture of Web service technologies for the.NET platform. ASP.NET provides ASMX, WSE is an extension to ASMX (really, simplya class library with custom configuration settings and a wizard), and WCF is anew technology stack hooked through the ASP.NET pipeline (for HTTPcommunication), but has its own processing model apart from ASP.NET.

 

Figure 1 illustrates the core components of all threetechnology stacks for a simple Web service and client. If you compare ASMX,ASMX with WSE, and WCF, from a high level they share similar architecturalfeatures:

  • All three expose an endpoint, either .asmx or.svc, for Web services hosted in IIS. For Windows Vista and Windows Longhorn Server, you can also host with the Windows Activation Service (WAS); this alsorequires an endpoint.

  • The service endpoint is associated with aservice type that holds the code for each operation. In the case of .asmxendpoints, it s a type that inherits the WebService base type and implementsthe WebServiceAttribute from the System.Web.Services namespace. In the case of.svc endpoints, it s a type that implements a service contract using theServiceContractAttribute from the System.ServiceModel namespace.

  • If the implementation is well designed, theservice type never includes actual business logic. Instead, the service is thewindow through which business assemblies can be invoked a service-orientedboundary, if you will.

  • All three produce WSDL documents that describethe Web service contract. This document can be used by proxy generators for anyWeb service platform to generate code to communicate with the Web service.

  • All three include a proxy generator that cangenerate the necessary proxy code and configuration settings to communicate tothe Web service to which the WSDL document points. Proxies in all cases areessentially wrappers for service operations and messages, converted to methodswith parameters and a return value that can be represented as the messageschema on the wire. Each technology provides a different proxy base type thathandles the heavy lifting of serialization and deserialization(System.Web.Services.Protocols.SoapHttpClientProtocol,Microsoft.Web.Services3.WebServicesClientProtocol, and System.ServiceModel.ClientBase,respectively).

 


Figure 1: Architectural comparisonof ASMX, ASMX with WSE, and WCF.

 

Migrating code from ASMX with WSE to WCF isn t much of astretch from this perspective. In the simplest view, you are swapping .asmx for.svc, WebServiceAttribute/WebService for ServiceContractAttribute, and ASMX/WSEconfiguration for WCF configuration. The business logic remains the same. Ofcourse, there is a learning curve involved, so it is important to evaluate theneed to move from one technology to the other.

 

Support for Web Service Protocols

Compatibility between ASMX, ASMX with WSE, WCF, and other Webservice platforms, and their respective value, really boils down to protocolsupport. After you ve overcome the hurdle of the application architecture, whatyou really need to establish are the desired protocols you wish to support foreach service.

 

The primary point of compatibility is in the serviceoperations and the actual message schemas that define the input (parameters)and output (return value) message for each. This requires agreement on SOAP andWSDL only. But, once we begin talking about security, message encoding formats,reliability, transactions, and other facets of Web service messaging, you must lookmore closely at the standards being applied and compatibility betweenplatforms.

 

In reality, today s Web services largely apply ratifiedstandards for messaging and security, including WS-Addressing, MTOM, and OASISWeb Service Security (WSS). These standards are implemented by WSE 3.0 and WCF.There are, however, important standards emerging that will improve security,reliability, and system consistency and these will not be implemented in WSE3.0. Thus, as a forward-thinking approach, WCF is a necessity.

 

You should also look at each platform for its overallvalue in your system development efforts. Although ASMX with WSE 3.0 may solvemost of today s Web service requirements, they still aren t viable technologiesfor distributed communications behind the firewall. Instead of learning .NETremoting or Enterprise Services for those other cases, WCF can be applied toany distributed communication setting. In this way, you are investing inlearning a single communication stack, designing services independent ofdeployment protocol, and later deploying those services as either Web servicesor as endpoints available over named pipes, TCP, MSMQ, or any other customprotocol. The table in Figure 2 compares the protocols supported by ASMX withWSE and WCF.

 

Feature

ASMX/WSE 3.0

WCF

Transport Protocols

HTTP, HTTPS, TCP

HTTP, HTTPS, TCP, Named Pipes (IPC), MSMQ

Message Encoding

Text, MTOM, DIME (obsolete)

Text, MTOM, Binary

Web Service Protocols

SOAP, WSDL, WS-Addressing, MTOM, OASIS WS-Security, WS-Trust, WS-SecureConversation, SAML

SOAP, WSDL, WS-Addressing, MTOM, OASIS WS-Security, WS-Trust, WS-SecureConversation, SAML, WS-ReliableMessaging, WS-AtomicTransaction

Figure 2: Theprotocols supported by ASMX with WSE and WCF.

 

WSE and WCF are extensible environments that can supportcustom transport protocols, message encoding formats, and other messagingprotocols. Still, WSE is not considered a viable option for binary distributedcommunication over TCP (as is WCF); in particular, because WCF supports systemprogramming features for security, reliability, and transactions equivalent towhat Enterprise Services supports.

 

Getting Started with WCF

There is a learning curve involved when you move to WCF.Some of the basic things you ll have to master are:

  • Designing service contracts

  • Serializing complex types

  • Host configuration settings

  • Proxy generation

 

In fact, WCF isn t any harder to master than ASMX or WSE it simply has more features than the two put together, because it also supports.NET remoting and Enterprise Services scenarios. Just as you would explore the Webservice standards supported by WSE to employ them, you ll do the same with WCF.Just as you would explore security boundaries and distributed transactions withEnterprise Services, you ll do the same with WCF.

 

Having said that, what follows is a quick step-by-stepintroduction to a basic WCF Web service to give you a taste equivalent towhat you would have with ASMX.

 

Installing Support for WCF

Before you can develop with WCF you must install, in thisorder, the necessary .NET 3.0 technologies:

  • Microsoft .NET Framework 3.0 Runtime (alreadyinstalled on Windows Vista machines)

  • Microsoft Windows SDK for Vistaand .NET Framework 3.0

  • Visual Studio 2005 Extensions for .NET Framework3.0 (WCF and WPF)

 

The Visual Studio extensions provide WCF project andservice templates to assist you.

 

Creating a WCF Service Project

You can add a new WCF Service to an existing ASP.NET Website, or create a new Web site using the WCF Service template shown in Figure 3.

 


Figure 3: Creating a new WCF Serviceproject.

 

This WCF Service template generates a new ASP.NET Website, with a WCF service (in the same spirit as a new ASP.NET Web Servicetemplate produces a new ASMX Web service). WCF services hosted in IIS areexposed through a .svc endpoint instead of a .asmx endpoint (see Figure 4).

 


Figure 4: Files generated for a newWCF Service Web site.

 

The .svc file contains a reference to a service type,which can be a source file located in the App_Code directory:

 

<% @ServiceHost Service="MyService" CodeBehind="~/

 App_Code/Service.cs"%>

 

You can also supply a service type that belongs to anotherassembly referenced by the Web site:

 

<% @ServiceHost Service= MyNamespace.MyService %>

 

In either case, the service type is a class thatimplements a service contract.

 

Creating a Service

A service contract is simply a definition for a set ofoperations for a service. As with ASMX, you should define an interface withthose operations, then implement the interface on a service type. Here is theservice contract generated by the WCF Service template:

 

using System;

using System.ServiceModel;

[ServiceContract()]

public interface IMyService

{

    [OperationContract]

   stringMyOperation1(string myValue1);

    [OperationContract]

   stringMyOperation2(DataContract1 dataContractValue);

}

 

Service contracts are marked with theServiceContractAttribute from the System.ServiceModel namespace. In addition,you ll have one or more methods in the interface, marked with theOperationContractAttribute to indicate they should be included in the WSDLcontract for the service that implements this contract. In this example,DataContract1 is a complex type that is passed to MyOperation2. (I won t divein to complex types and serialization in this overview.)

 

To implement the contract, provide a class that implementsthe service contract interface. Here is the implementation provided in thegenerated code:

 

public class MyService : IMyService

{

 public stringMyOperation1(string myValue1)

 {

     return "Hello:" + myValue1;

 }

 public stringMyOperation2(DataContract1 dataContractValue)

 {

     return "Hello:" + dataContractValue.FirstName;

 }

}

 

You ve seen a service contract and a serviceimplementation. What s interesting is that I didn t simply show you how tocreate a WCF Web service I showed you how to create a service that can belater hosted in IIS over HTTP as a traditional Web service, or hosted behindthe firewall as a distributed TCP endpoint using binary serialization!

 

Hosting a Service

Following the steps so far, you have a service contract, aservice type, and a service host (the Web site). In the web.config file apreliminary configuration has been created for the new service, inside the section. This is the section that contains configuration settings for your WCFservices hosted by the application. The configuration should look like Figure 5to more-or-less mimic an ASMX Web service endpoint.

 

 

       "serviceBehavior">            "basicHttpBinding"/>             binding="mexHttpBinding"/>                                         Figure 5: Mimic anASMX Web service endpoint.   In summary, the configuration section does the following: Exposes a BasicHttpBinding endpoint. An endpointdescribes the address, binding, and contract. The address in this case is the.svc file. The binding describes the protocols used to access the service. Inthis case, the default settings for BasicHttpBinding are used, which means HTTPprotocol is used to access the service, and that no WS* security features areenabled. The contract indicates which operations will be accessible by thisendpoint. Supplies a ServiceDebugBehavior, enablingexceptions to be reported to callers. This is consistent with ASMX, in thatexceptions are wrapped as SOAP faults so the client can inspect them. It isrecommended this be disabled in production environments (a deeper subject for alater time). Supplies a ServiceMetadataBehavior, enablingHTTP GET access, so the service endpoint can be browsed to with access to thegenerated WSDL document. This is consistent with ASMX. Exposes a metadata exchange endpoint so thatclients can generate a proxy using metadata exchange instead of using the WSDLdocument. This must be enabled to add a service reference, which I ll describenext.   If you edit the automatically generated configuration fileto reflect these settings, you ll be able to browse to the Service.svc endpoint,as shown in Figure 6.  
Figure 6: Browsing to a WCF serviceendpoint.  Generating a Proxy The final step in this crash tour for creating andconsuming WCF Web services is to look at how clients consume the service. Aswith ASMX, there is a way to generate a WCF proxy to invoke the service insteadof using a .NET 2.0 or WSE proxy. After creating a client application, insteadof adding a Web Reference, you ll add a Service Reference, as shown in Figure 7.  
Figure 7: Adding a service reference.   This generates a proxy that inherits ClientBaseas discussed in Figure 1. It also generates a configuration for the client thatindicates the service endpoint and the type of protocols to use, namely, BasicHttpBinding,as shown here:            Service.svc"binding="basicHttpBinding"     contract="WCFClient.localhost.IMyService"  />     The proxy is initialized with this configuration whenconstructed; combined with the metadata of the service contract, this is enoughfor it to know how to send and receive messages between client and service. Thefollowing few lines of code is all it takes to invoke the service:  localhost.MyServiceClient proxy = newWCFClient.localhost.MyServiceClient();string s = proxy.MyOperation1("WCF Client");  Introducing Exploring WCF Web Services At this point you ve seen the basics for creating andconsuming WCF Web service endpoints, with some comparisons drawn to ASMX. Thissimple walkthrough reduces the complexity of WCF by focusing on a single goal,replacing what ASMX gives you. Clearly there is more to this learning curve aswe have not yet discussed serialization of complex types, how to achievesimilar results as with your favorite WSE scenarios, and how to weigh andincorporate the vast number of additional configuration buttons and knobsprovided by WCF. It is undoubtedly the richest communication platform we haveseen to date. Luckily, if you focus on specific scenarios, such as themigration of existing ASMX or ASMX with WSE services, it is possible to isolateWCF service design and configuration elements to help you on your way.   WCF will most definitely have an impact on how youapproach developing Web services going forward. At asp.netPRO we want to provide you with a dedicated column titled ExploringWCF Web Services that will help you migrate successfully from ASMX and WSE toWCF, teach you the basics, discuss ASP.NET compatibility, and help tackleadvanced concepts. Feel free to send questions, as always, to [email protected] foryour ASP.NET topics and for WCF topics as they relate to Web servicedevelopment. We re listening! Thanks for reading!  Michele LerouxBustamante is Chief Architect at IDesign Inc., Microsoft Regional Directorfor San Diego, Microsoft MVP for Connected Systems, and a BEA TechnicalDirector. At IDesign Michele provides training, mentoring, and high-endarchitecture consulting services, specializing in scalable and secure .NETarchitecture design, globalization, Web services, and interoperability withJava platforms. She is a board member for the International Association ofSoftware Architects (IASA), a frequent conference presenter, conference chairof SD s Web Services and Web Development tracks, and a frequently publishedauthor. Michele recently completed the book LearningWCF, published by O Reilly (book blog: http://www.thatindigogirl.com). Reachher at http://www.idesign.net or http://www.dasblonde.net.  Additional Resources WSE Developer Center:http://msdn.microsoft.com/webservices/webservices/building/wse/default.aspx WCF Home: http://wcf.netfx3.com Michele s blog: http://www.dasblonde.net Michele s WCF book: http://www.thatindigogirl.com IDesign: http://www.idesign.net      

Read more about:

Microsoft
Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like