Introduction
This blog post discusses some of the differences between WCF and ASMX Services.
Windows Communication Foundation
WCF provides a common platform for all .NET communication.
It is a programming platform and runtime system for building, configuring and deploying network-distributed services. It is the latest service oriented technology; Interoperability being one of its fundamental characteristics. It is a combined set of features including Web Services, Remoting, MSMQ and COM+.
The figure below shows the different technologies combined to form WCF.

ASMX Web Services
are published, described and located over Internet. An ASMX web service is a collection of protocols and standards used for exchanging data between applications or systems with following characteristics:
1. A Web Service is a piece of executable code that is accessible over the Web.
2. A Web Service can communicate using platform-independent and language-neutral Web protocols.
3. A Web Service can share schemas and contracts/interface which in turn can be called from another program.
4. A Web Service can be registered and located through a Web Service Registry.
5. A Web Service supports loosely coupled connections between systems.
Conceptual Differences
The conceptual difference between WCF and ASMX Services can be highlighted under following points
Protocols Support
- WCF
- HTTP
- TCP
- Named pipes
- MSMQ
- Custom
- UDP
- ASMX
Hosting
- ASMX
- Can be hosted only with HttpRuntime on IIS.
- WCF
- A WCF component can be hosted in any kind of environment in .NET 3.0, such as a console application, Windows application, or IIS.
- WCF services are known as 'services' as opposed to web services because one can host services outside of a web (HTTP) server.
- Self-hosting the services gives one the flexibility to use transports other than HTTP
Advantages of WCF over ASMX Services
-
Better Interoperability
WCF is interoperable with other services when compared to .Net Remoting,where the client and service have to be .Net.
-
End-to-End Reliability and Security:
WCF services provide better reliability and security in comparison to ASMX web services.
-
Configuration based security and binding:
In WCF, there is no need to make changes in code for implementing the security model or changing the binding. Small configuration changes are all that is needed.
-
Integrated Logging:
WCF has an integrated logging mechanism, changing the configuration file settings provides logging functionality. In ASMX (and other technologies), one has to write logging specific code.
-
Multiple Protocols:
WCF works across multiple protocols including http, tcp, MSMQ etc where as ASMX services can only use http.
-
Transactional Capability:
WCF can create and maintain transactions like com+ .
-
Hosting Options:
WCF services can be hosted on IIS, Self hosting, Windows Services(Windows Application Service) and even console apps, WinForms apps etc.
-
Better Interoperability through Data Contracts
The development of web service with ASP.net relies on defining data and relies on the XMLSerializer to transform data to or from a service. WCF Uses DataContractAttribute and DataMember attributes to Translate .net types to XML.
DataContract attributes can be used for classes and structures-DataMember Attribute to Field or P
roperty
The differences between DataContractSerailizer and XML Serializer include:
- DCS has better performance over XML Serialization
- XML Serialization doesn't indicate which field or property of the type is serialized, DCS Explicitly shows which field or property is serialized
- DCS can serialize classes implementing IDictionary interface(Hash Table)
-
Exception Handling
In ASP.NET Web services, Unhandled exceptions are returned to the client as SOAP faults. In WCF Services, unhandled exceptions are not returned to clients as SOAP faults. A configuration setting is provided to have the unhandled exceptions returned to clients for the purpose of debugging.
Limitations of ASMX:
- An ASMX page doesn’t tell you how to deliver it over the transports or to use a specific type of security. WCF lets you choose that easily via configuration parameters.
- ASMX is tightly coupled to the HTTP runtime and has a strong dependence on IIS to host it. WCF can be hosted by any Windows process that is able to host the .NET Framework 3.0.
- ASMX services are instantiated on a per-call basis, while WCF gives one the flexibility by providing various instantiating options such as singleton, private session, per call.
- ASMX provides the way for interoperability but it does not provide guaranteed end-to-end security or reliable communication. WCF provides both end-to-end reliability as well as security.
WCF Architecture
The following figure illustrates the major components of WCF.
Contracts
Contracts are the closest layer to the Application layer. A developer will utilize this contract layer to develop a WCF service. We illustrate this through the example below. This example will show us what contracts will do for us that cannot be easily done in regular ASMX web services.
Service contracts
In every service oriented architecture, services share schemas and contracts, not classes and types (3rd SOA tenet). What this means is that you don't share class definitions neither any implementation details about your service to consumers. Everything your consumer has to know is your service interface, and how to talk to it. In order to know this, both parts (service and consumer) have to share something that is called a Contract. A contract must be seen as normalization for the service interface. A contract isn’t any kind of SLA – since it does not contain any details about the way your consumer calls the service (i.e. does not contain any transport level details).
When you expose any service, let us say an ASMX service for example, what you are exposing is a class, (that inherits from WebService) and which has some public methods that you decorate with WebMethod attribute. This process, indirectly, exposes a service contract. If you get the WSDL for your service, you will be able to see the service contract (an element with the name of your WebService (portType) as well as your web methods (operations)).
WCF, conceptually does the same thing. A WCF Service Contract describes what the service can do for you. It defines some properties about the service, and a set of actions called Operation Contracts. Operation Contracts are equivalent to web methods in ASMX technology, or, if you prefer, to the operation element in WSDL.
In WCF, contracts are interfaces (this is not completely true, since there is another way of indirectly declare service contracts, but you should assume it as a best practice), decorated with special attributes. Those special attributes are ServiceContract and OperationContract. As an example, lets assume you want a service named SumService in order to Sum two values. In WCF, you could define something like:
[ServiceContract()]
public interface ISumService
{
[OperationContract()]
double Sum(double val1, double val2);
}
When you're doing this, you're normalizing your service contract, and it's interface, by saying that you're exposing a Sum operation, which accepts two double arguments, and returns a double result.
By providing the above ServiceContract, we are effectively doing Contract First service development. The only thing special about WCF Service Contracts are the decoration attributes. These attributes identify the WCF service to the outside world.
If you wanted to implement an instance of your service contract, it would be as simple as to write your service implementation class which implements ISumService. That service would look something like:
public class SumService : ISumService
{
public double Sum(double val1, double val2)
{
return val1 + val2;
}
}
Data contracts
Service Contracts by default, can handle simple service calls. Calls which can have simple type arguments, and which return also simple types values. The problem comes when you want to return a complex type, or accept it as an argument for your service operation.
In order to do that, the messaging world, has a concept called Data Contract. Data Contract is the normalization of your custom messaging structures. It defines the members of your operation arguments or return values. In WSDL, a Data Contract is equivalent to the type element.
In WCF, Data Contracts are defined through classes instead of interfaces like Service Contracts. Those classes are decorated with an attribute named DataContract. Data members that are part of the message should be decorated with the DataMember attribute.
Let us suppose we have a service named MembershipService with an operation named GetUserDetails :
public class MembershipService
{
public User GetUserDetails(int userId)
{
//internal logical to get the User details…
}
}
In order to normalize the User serialization on the wire, we need to decorate the User class with the following attributes:
[DataContract]
public class User
{
[DataMember]
public string Name;
[DataMember]
public string Address;
//..etc..
}
You might wonder, why we need to decorate our class at all, since this was not needed in the ASMX web services world. In ASMX, we actually could have decorated with custom Xml attributes if we wanted to – but were never required to do so. If you chose not to decorate an ASMX service, by default, the framework would handle it for you and serialize the types over the wire (provided the types were serializable).
WCF assumes that nothing is exposed by default. So, if our class is not decorated with Data Contract attributes, WCF will not serialize it over the wire. This is a key difference, since it provides explicit control of what is being sent on the message to the developer.
Another feature of WCF Data Contracts is the option to define Required/NonRequired data members. This is done with a property named IsRequired on DataMember attribute. Using this property, we can define whether a member is mandatory or optional while receiving incoming messages using Data Contracts.
As an example, let us assume we have another operation called AddUser as part of our MembershipService.
public int AddUser(User userDetails)
{
//add the user and return the newly created userId ;
}
If your application demands that the user Name field is required, but Address is not, you could decorate the User Data Contract as such. The User DataContract would look like this:
[DataContract]
public class User
{
[DataMember(IsRequired = true)]
public string Name;
[DataMember(IsRequired = false)]
public string Address;
//..etc..
}
Message Contract
There are times where the default SOAP message format provided by the WCF runtime infrastructure does not meet our needs. In that case, we may want to manipulate the format of the actual SOAP message that is being passed between the client and the service. In other words, our message contracts allow us to specify what exactly a service will be passing on the wire. Prior to WCF, the only way to accomplish this is by plugging into the HTTP pipeline and intercepting the messages through SOAP extensions. However with the introduction of WCF message contracts, we now have a finer level of control over the SOAP messages in that we can easily demarcate the portions of the message that should live in the SOAP header and those that should live in the body.
In addition, the message contracts also provide us with a way to control how the WSDL is generated for a WCF service. By separating the message into two well defined sections (header and body), we now have the ability to apply different types of processing to these two sections. For example, we can apply different encryption processing to each section.
Here is an example of a message contract.
[MessageContract]
public class CategoryAttributes
{
[MessageHeader]
public DateTime ModifiedDate;
[MessageHeader]
public Guid guid;
[MessageBodyMember]
public string Name;
}
To start with, we decorate the name of the class that represents the SOAP message with the keyword MessageContract. When you apply a MessageContract attribute to a type, it is used to serialize a SOAP message. Applying the MessageHeader to data members creates one or more SOAP headers in the WSDL contract for this message. Applying the MessageBodyMember creates one or more SOAP body elements that can be ordered using the System.ServiceModel.MessageBodyMember.Order property of the attribute. For example, to order the Name property to appear before the AnotherProperty, we can use the Order attribute to indicate their specific locations.
[MessageContract]
public class CategoryAttributes
{
[MessageHeader]
public DateTime ModifiedDate;
[MessageHeader]
public Guid guid;
[MessageBodyMember(Order = 1)]
public string Name;
[MessageBodyMember(Order = 2)]
public string AnotherProperty;
}
Fault Contracts
There are times where we may want to return custom SOAP faults to clients so that you can provide detailed information about the exceptions generated by the services. To accomplish this, we need to follow the steps below:
- Define a type using the data contract and specify the fields you want to return as part of the SOAP faults.
- Next, decorate the service operation with the FaultContract attribute and specify the name of the type defined in the first step.
- Raise the exception from the service by creating an instance of the type (defined in step 1) and set its properties to appropriate values.
To understand the fault contracts, consider the following EmployeeService implementation.
[ServiceContract]
public interface IEmployeeService
{
[OperationContract]
[FaultContract(typeof(EmployeeException),
Action = "http://cut.ms/YDO,
ProtectionLevel = ProtectionLevel.EncryptAndSign)]
int AddEmployee(string employeeName, DateTime modifiedDate,
Guid guid);
}
By decorating the service operation with the FaultContract attribute, we are instructing WCF to include the appropriate fault information in the service metadata (specifically in the XSD and WSDL).
Once we specify the fault contract, whenever we raise the EmployeeException from the service implementation, the exception will get serialized into custom SOAP fault message, which is then propagated back up to the caller.
throw new FaultException<EmployeeException>(newEmployeeException
("Employee Name 1", "Employee Exception Message 1"));
In the above code, the FaultException type is used to throw the EmployeeException to the caller. Now that we have seen the service code, let us briefly look at the client code required to handle and process the exception.
public static void Main()
{
EmployeeServiceClient client= newEmployeeServiceClient();
try
{
client.AddEmployee("Test Employee", DateTime.Now,
System.Guid.NewGuid());
MessageBox.Show("Employee added");
}
catch(FaultException<EmployeeException> employeeException)
{
//Process the exception
}
}
On the client, we catch the EmployeeException and process the details of the exception in the catch block like you would catch any other exception.
Policies and Binding
Lets you specify conditions required to communicate with a service e.g security requirement to communicate with service, protocol and encoding used for binding.
WCF Service Runtime
The service runtime contains the behaviors that occur during runtime of service.
- Throttling Behavior- Controls how many messages are processed.
- Error Behavior - Specifies what to do when internal error occurs on the service.
- Metadata Behavior - Tells us how to display metadata to the outside world.
- Instance Behavior - Specifies how many instance of the service have to be created while running.
- Transaction Behavior - Enables the rollback of transacted operations if a failure occurs.
- Dispatch Behavior - Controls how a message is processed by the WCF Infrastructure.
Messaging
The messaging layer is composed of channels. A channel is a component that processes a message in some way, for example, by authenticating a message. A set of channels is also known as a channel stack. Channels are the core abstraction for sending message to and receiving message from an Endpoint. Broadly we can categorize channels as
-
Transport Channels
Handles sending and receiving message from network protocols like HTTP, TCP, name pipes and MSMQ.
-
Protocol Channels
Implements SOAP based protocol by processing and possibly modifying message. E.g. WS-Security and WS-Reliability.
Activation and Hosting
- Services can be hosted or executed in order to be made available to various client types. WCF services can be hosted by any of the following mechanisms:
-
IIS
Internet information Service provides a number of advantages if a service uses Http as protocol. It does not require Host code to activate the service - it automatically activates the service code.
-
Windows Activation Service
(WAS) is a new process activation mechanism that ships with IIS 7.0. In addition to HTTP based communication, WCF can also use WAS to provide message-based activation over other protocols, such as TCP and named pipes.
-
Self-Hosting
WCF service can be self hosted as console application, WinForms or WPF application with graphical UI.
-
Windows Service
WCF can also be hosted as a Windows Service, so that it is under control of the Service Control Manager (SCM).
Creating a Service Contract in ASMX
The ASMX framework in the .NET Framework 2.0 introduces a significant programming model improvement: the ability to define your Web service contracts in .NET interface definitions. This feature allows one to annotate .NET interface definitions with the usual System.Web.Services attributes ([WebServiceBinding], [WebMethod], [SoapDocumentMethod], and so forth). One can then implement the .NET interface on a .NET class to effectively implement the service contract.
This approach is very similar to the one in WCF (the main difference being the attribute names). It allows us to decouple the service contract from the implementation code, thereby making things easier to manage and reuse over time and making the code more readable. An Example of this approach-
using System.Web.Services;
[WebServiceBinding(
Name= "QuoteService",
Namespace= "http://cut.ms/YDP,
ConformsTo = WsiProfiles.BasicProfile1_1,
EmitConformanceClaims = true)]
public interfaceIQuoteService
{
[WebMethod]
StockQuote GetQuote(stringsymbol);
[WebMethod]
List<StockQuote> GetQuotes(List<string> symbols);
}
[WebService(Namespace= "http://cut.ms/YDP)]
public classQuoteService : IQuoteService
{
publicStockQuote GetQuote(stringsymbol)
{
... // retrieve and return new StockQuote
}
publicList<StockQuote> GetQuotes(List<string> symbol)
{
... // retrieve and return List<StockQuote>
}
}
In WCF, we always attribute the ServiceContract on the interface – this is a key feature that lets us host our WCF service in multiple hosts as opposed to just an HTTP host.
As illustrated above, [WebServiceBinding] and [WebMethod] both go on the interface while [WebService] goes on the class. When employing this model, all attributes that affect the service contract definition must be placed on the interface definition and not on the class. This includes [SoapDocumentService], [SoapDocumentMethod], and the various System.Xml.Serialization attributes that we could possibly apply to method signatures. These attributes cannot be mixed and matched across the interface and class definitions.
For example, once we have derived a class from an interface that contains these service contract attributes, ASMX will inspect the class at run time to make sure that you haven't used any additional attributes that might further change the service contract. If ASMX finds one, it will display an error indicating you've violated the model see Figure
Although this minimizes the number of attributes you'll need to use on the derived class, there are still a few that come into play for configuring the service endpoint. We will use [WebService] on the class to specify the <wsdl:service> details of the endpoint. This makes sense because we could have multiple services implementing the same service contract. Likewise, if we are using WSE 3.0, we will use [Policy] on the class to apply a security policy configuration to the specific endpoint.
The use of [WebMethod] does not affect the service contract. It is simply configuring local processing behavior. When using [WebMethod] in this context, we can only use these behavioral properties and must avoid anything that could modify the service contract.
Differences from Security Point of View
The options for securing ASMX Web services are the same as those for securing any IIS application. Because WCF applications can be hosted not only within IIS but also within any .NET executable, the options for securing WCF applications must be made independent from the facilities of IIS. However, the facilities provided for ASP.NET Web services are also available for WCF services running in ASP.NET compatibility mode.
Security: Authentication
IIS provides facilities for controlling access to applications whereby we can select either anonymous access or a variety of modes of authentication: Windows Authentication, Digest Authentication, Basic Authentication, and .NET Passport Authentication. The Windows Authentication option can be used to control access to ASP.NET Web services. However, when WCF applications are hosted within IIS, IIS must be configured to permit anonymous access to the application, so that authentication can be managed by WCF itself, which does support Windows authentication among various other options. The other options that are built-in include username tokens, X.509 certificates, SAML tokens, and CardSpace card. Custom authentication mechanisms can also be defined.
Security: Impersonation
ASP.NET provides an identity element whereby an ASP.NET Web service can be made to impersonate a particular user or whichever user’s credentials are provided with the current request. That element can be used to configure impersonation in WCF applications running in ASP.NET compatibility mode.
The WCF configuration system provides its own identity element for designating a particular user to impersonate. Also, WCF clients and services can be independently configured for impersonation. Clients can be configured to impersonate the current user when they transmit requests.
<behaviors>
<behaviorname="DerivativesCalculatorClientBehavior">
<clientCredentials>
<windows allowedImpersonationLevel="Impersonation"/>
</clientCredentials>
</behavior>
</behaviors>
Service operations can be configured to impersonate whichever user’s credentials are provided with the current request.
[OperationBehavior(Impersonation = ImpersonationOption.Required)]
public void Receive(Message input)
Security: Authorization using Access Control Lists
Access Control Lists (ACLs) can be used to restrict access to .asmx files. However, ACLs on WCF .svc files are ignored except in ASP.NET compatibility mode.
Security Comparison: Role-based Authorization
The IIS Windows Authentication option can be used in conjunction with the authorization element provided by the ASP.NET configuration language to facilitate role-based authorization for ASP.NET Web services based on the Windows groups to which users are assigned. ASP.NET 2.0 introduced a more general role-based authorization mechanism: role providers.
Role providers are classes that all implement a basic interface for enquiring about the roles to which a user is assigned, but each role provider knows how to retrieve that information from a different source. ASP.NET 2.0 provides a role provider that can retrieve role assignments from a Microsoft SQL Server database, and another that can retrieve role assignments from the Windows Server 2003 Authorization Manager.
The role provider mechanism can actually be used independently of ASP.NET in any .NET application, including a WCF application. The following sample configuration for a WCF application shows how the use of an ASP.NET role provider is an option selected by means of the ServiceAuthorizationBehavior.
<system.serviceModel>
<services>
<service name="Service.ResourceAccessServiceType"
behaviorConfiguration="ServiceBehavior">
<endpoint
address="ResourceAccessService"
binding="wsHttpBinding"
contract="Service.IResourceAccessContract"/>
</service>
</services>
<behaviors>
<behavior name="ServiceBehavior">
<serviceAuthorization principalPermissionMode="UseAspNetRoles"/>
</behavior>
</behaviors>
</system.serviceModel>
Security Comparison: Claims-based Authorization
One of the most important innovations of WCF is its thorough support for authorizing access to protected resources based on claims. Claims consist of a type, a right and a value, a drivers’ license, for example. It makes a set of claims about the bearer, one of which is the bearer’s date of birth. The type of that claim is date of birth while the value of the claim is the actual driver’s birth date. The right that a claim confers on the bearer specifies what the bearer can do with the claim’s value. In the case of the claim of the driver’s date of birth, the right is possession: the driver possesses that date of birth but cannot, for example, alter it. Claims-based authorization encloses role-based authorization, because roles are a type of claim.
Authorization based on claims is accomplished by comparing a set of claims to the access requirements of the operation and, depending on the outcome of that comparison, granting or denying access to the operation. In WCF, we can specify a class to use to run claims-based authorization, once again by assigning a value to the ServiceAuthorizationManager property of ServiceAuthorizationBehavior.
<behaviors>
<behavior name='ServiceBehavior'>
<serviceAuthorization
serviceAuthorizationManagerType=
'Service.AccessChecker, Service' />
</behavior>
</behaviors>
Classes used to run claims-based authorization must derive from ServiceAuthorizationManager, which has just one method to override, AccessCheck(). WCF calls that method whenever an operation of the service is invoked and provides a OperationContext object, which has the claims for the user in its ServiceSecurityContext.AuthorizationContext property. WCF does the work of assembling claims about the user from whatever security token the user provided for authentication, which leaves the of task of evaluating whether those claims suffice for the operation in question.
That WCF automatically assembles claims from any kind of security token is a highly significant innovation, because it makes the code for authorization based on the claims entirely independent of the authentication mechanism. By contrast, authorization using ACLs or roles in ASP.NET is closely tied to Windows authentication.
Security Comparison: Confidentiality
The confidentiality of messages exchanged with ASP.NET Web services can be ensured at the transport level by configuring the application within IIS to use the Secure Hypertext Transfer Protocol (HTTPS). The same can be done for WCF applications hosted within IIS. However, WCF applications hosted outside of IIS can also be configured to use a secure transport protocol. More important, WCF applications can also be configured to secure the messages before they are transported, using the WS-Security protocol. Securing just the body of a message using WS-Security allows it to be transmitted confidentially across intermediaries before reaching its final destination.
Transport Differences
ASMX services use the HTTP transport protocol for communications with Internet Information Services (IIS) as the host. An ASMX service file has the file name extension .asmx, which is accessed using a Uniform Resource Locator (URL); for example, http://cut.ms/YDT
WCF services can also use the HTTP protocol, but unlike ASMX services, we also have the option to use other transport protocols. The following protocols are supported by WCF:
- Hypertext Transfer Protocol (HTTP)
- Transmission Control Protocol (TCP)
- Message Queuing (also known as MSMQ)
- Named pipes
Many different hosts can also be used with WCF services. For example, IIS can be used as a host with the HTTP transport protocol. Windows services and stand-alone applications can be used as a host for other transport protocols.
Accessing a service hosted in IIS is similar to accessing an ASMX service; for example, http://cut.ms/YDU
The only difference between the two services is the file name extension. However, you can also configure a WCF service to use the .asmx file name extension, as described in the Service Configuration topic. WCF services that use other transport protocols are accessed using methods associated with the specific protocol.
When migrating an ASMX service to WCF, the protocol you choose is based on the client applications that will be accessing the service. If you need to support ASMX client applications, you also need to use the HTTP protocol. In addition, when configuring a WCF service for ASMX client applications, you need to configure the service to use BasicHttpBinding, as described in the Service Configuration topic.
Recommendation for Migrating from ASMX to WCF
When migrating services from ASMX to WCF, if ASMX client applications need to access the migrated service, use the HTTP protocol and configure the new service to use BasicHttpBinding.
Choosing the right WCF binding
A WCF binding is the endpoint component that defines how the client needs to communicate with the service. It groups settings such as underlying transport protocol, security requirements and message encoding.
WCF provides nine built-in bindings:
-
BasicHttpBinding:
Basic web service communication. Exposes WCF services as legacy ASMX web services. Used for interoperability. No security by default.
-
WSHttpBinding:
Web services with WS-* support. Supports transactions and reliable messaging.
-
WSDualHttpBinding:
Web services with duplex contract and transaction support.
-
WSFederationHttpBinding:
Web services with federated security. Supports transactions.
-
MsmqIntegrationBinding:
Communication directly with MSMQ applications. Supports transactions.
-
NetMsmqBinding:
Communication between WCF applications by using queuing. Supports transactions.
-
NetNamedPipeBinding:
Communication between WCF applications on same computer. Supports duplex contracts and transactions.
-
NetPeerTcpBinding:
Communication between computers across peer-to-peer services. Supports duplex contracts.
-
NetTcpBinding:
Communication between WCF applications across computers. Supports duplex contracts and transactions.

Endpoints
A Service Endpoint has an Address, a Binding and a Contract.
The Endpoint's Address is a network address where the Endpoint resides. The EndpointAddress class represents a WCF Endpoint Address.
The Endpoint's Binding specifies how the Endpoint communicates with the world including things such as transport protocol (e.g., TCP, HTTP), encoding (e.g., text, binary) as well as security requirements (e.g., SSL, SOAP message security). The Binding class represents a WCF Binding.
The Endpoint's Contract specifies what the Endpoint communicates and is essentially a collection of messages organized in operations that have basic Message Exchange Patterns (MEPs) such as one-way, duplex, and request/reply. The ContractDescription class represents a WCF Contract.
The ServiceEndpoint class represents an Endpoint and has an EndpointAddress, a Binding as well as a ContractDescription corresponding to the Endpoint's Address, Binding, and Contract, respectively

Defining Endpoints
Endpoints can be defined in code or in configuration files. In the example below, the DefineEndpointImperatively method shows the easiest way to define Endpoints in code and start the service.
DefineEndpointInConfig method shows the equivalent endpoint defined in config (config example follows the code below).
public class WCFServiceApp
{
public void DefineEndpointImperatively()
{
//create a service host for MathService
ServiceHost sh = new ServiceHost(typeof(MathService));
//use the AddEndpoint helper method to
//create the ServiceEndpoint and add it
//to the ServiceDescription
sh.AddServiceEndpoint(
typeof(IMath), //contract type
new WSHttpBinding(), //one of the built-in bindings
"http://cut.ms/YDY); //the endpoint's address
//create and open the service runtime
sh.Open();
}
public void DefineEndpointInConfig()
{
//create a service host for MathService
ServiceHost sh = new ServiceHost (typeof(MathService));
//create and open the service runtime
sh.Open();
}
}
<!-- configuration file used by above code -->
<configuration
xmlns="http://cut.ms/YDZ">
<system.serviceModel>
<services>
<!-- service element references the service type -->
<service type="MathService">
<!-- endpoint element defines the ABCs of the endpoint -->
<endpoint
address="http://cut.ms/YD0"
binding="wsHttpBinding"
contract="IMath"/>
</service>
</services>
</system.serviceModel>
</configuration>
Recommended procedure for creating a custom transport in WCF
ASMX services only implement BasicHttpBinding and though we have seen an implementation of Service Contract there’s no concept of contracts in ASMX.
Other important Coding Differences
The WCF uses the DataContractAttribute and DataMemeberAttribute to translate .NET types in to XML.
[DataContract]
public classItem
{
[DataMember]
public string ItemID;
[DataMember]
public decimal ItemQuantity;
[DataMember]
public decimal ItemPrice;
}
The DataContractAttribute can be applied to the class or a strcture.DataMemberAttribute can be applied to field or a property and theses fields or properties can be either public or private.
Important difference between DataContractSerializer and XMLSerializer.
- A practical benefit of the design of the DataContractSerializer is better performance over XMLserialization.
- XMLSerialization does not indicate the which fields or properties of the type are serialized into XML where as DataCotratSerializer Explicitly shows the which fields or properties are serialized into XML.
- The DataContractSerializer can translate the HashTable into XML.
Actual Coding of the Service
ASMX
To develop a service using ASMX services, we must add the WebService attribute to the class and WebMethodAttribute to any of the class methods.
[WebService]
public class Service : System.Web.Services.WebService
{
[WebMethod]
public string Test(string strMsg)
{
return strMsg;
}
}
WCF
To develop a service in WCF we will write the following code
[ServiceContract]
public interface ITest
{
[OperationContract]
string ShowMessage(string strMsg);
}
public class Service : ITest
{
public string ShowMessage(string strMsg)
{
return strMsg;
}
}
The ServiceContractAttribute specifies that a interface defines a WCF service contract, OperationContract Attribute indicates which of the methods of the interface defines the operations of the service contract.
A class that implements the service contract is referred to as a service type in WCF.
Comparison Table: WCF and ASMX
Here is a comparison between using both technologies to create a web service with basic profile binding:
| Feature |
ASMX |
WCF |
Comments |
| Easy to learn and code |
 |
 |
Both have similar attributes that are added to service and data classes |
| Easy to configure |
 |
|
WCF adds a host of configuration keys with different options that mostly are not useful |
| Easy to deploy |
 |
|
With several configuration and coding options, WCF is relatively harder to code and deploy. |
| Easy to browse and test |
 |
|
ASMX services provide a page to easily browse the services operations and enable users to test these operations from the browser. It also shows a full sample of the SOAP HTTP message to call the service simplifying life for developers who are trying to send these requests manually (mostly because their development platform doesn’t support it). Since WCF services are not necessarily HTTP based, they cannot be always browsed. |
| Easy to debug errors |
 |
|
Using WCF introduces a set of exceptions that maximize the complexity of working with the technology. |
| Compatibility with older .NET Frameworks |
 |
|
Trying to call a WCF service from .NET Framework 1.1 or 2.0 runs into difficulties – since WCF support only arrived with .NET 3.0. |
| ASP.NET Context |
 |
 |
In WCF this is off by default, so we have to add some compatibility configurations to be able to access the ASP.NET context which contains: Cache, Session, Cookies, Request headers specially host address. |
| Support for JSON data format |
 |
 |
Both added JSON support in .NET 3.5 to support calling the service from javascript |
| Support for WS-* standards |
|
 |
Support built into WCF – with ASMX it is possible to use WS-* – but a lot harder. |
| Support for binary data format |
|
 |
Although there are some issues to overcome, binary data transfers are more useful for large binary file transfers than XML. |
| Support for REST |
|
 |
REST as opposed to JSON is just a way in which HTTP requests are sent with parameters inside URLs. REST uses multiple HTTP actions instead of just GET. |
| Intercepting messages across the service/client |
|
 |
WCF support creating code that runs in certain events to intercept messages and processes them across all service operations.
This is not available in ASMX and could be useful in certain complex scenarios like doing custom authentication, authorization, logging and routing techniques. |
| Customizing client side functions |
|
 |
WCF enables you to take the service interface through a class library and use it to call the service without adding a service reference (using a dynamic channel factory). This allows using the same data classes in both the service and client, making it possible to include functionality in these classes (like caching, validation or auto calculated properties) that can be used on the client side.
This cannot be done using ASMX as it can only be called from the web reference which creates a copy of the data classes (taking only fields that are transferred on wires) without any functionality that was on the service classes. |
ASMX versus WCF Summary:
After this comparison, one point that emerges is the following: if you are using SOAP Basic Profile which is the most probable, you can continue using ASMX for it’s simplicity and ease of use unless you need a feature that only exists in WCF. This will save your project additional WCF related coding and configuration.
However, if you do have needs such as making your service available both inside an HTTP Server as well as inside another host (e.g. a WinForms app) or you need specific WS-* standard support, WCF is your only option.
Also, if you are using your service to send large documents back and forth (e.g. reports in pdf form passed from the server to the client), WCF’s binary data format can be useful.
If end-to-end reliability and security are concerns for your services, they are easier to implemented with WCF than with ASMXs.
Note: Another tip, if you are already using WCF with the default binding wsHttpBinding and you are not making use of any special feature of this binding (using only features like old ASMX). It’s better to change this binding to httpBasicProfile as this will greatly enhance the performance of your service.