Combining AJAX and WCF 2.0

The WCF "Orcas" release (the WCF from .NET Framework 3.5 aka WCF 2.0) makes it so much easier to use your WCF service in conjunction with ASP.NET AJAX (formerly known as ‘Atlas’).

Before Orcas you would build a AJAX enabled (web) service by adding the [ScriptService] attribute to the service class.

[WebService]

[ScriptService]

public class MyService

{

  // Implementation details

}

The ScriptServiceAttribute enables you to reference a JavaScript proxy from your client-side JS by including

Notice the /js that is appended at the end. That bit is the work of the ScriptService attribute. You do not have to add the script element manually, but get that automatically when you add a service reference to the ScriptManager control in your page.

Before anything will work all .asmx requests in an AJAX-enabled website are redirected to a different handler:

<system.web>

  <httpHandlers>

    <remove verb="*" path="*.asmx"/>

    <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, …"/>

    <add verb="*" path="*_AppService.axd" validate="false" type=""/>

    <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, …" validate="false"/>

  </httpHandlers>

</system.web>

This replacement .asmx handler will return JSON data instead of the usual SOAP enveloppes, allowing for easy usage from the JavaScript code.

<Side.note>

Here is a bit of JSON (JavaScript Object Notation) data:

{ "Name" : "Alex", "Age" : 35 }

Did you know that this is actually just a JavaScript fragment? Take a look at this:

var person = { "Name" : "Alex", "Age" : 35 };

window.alert(person.Age);

So, when you send some JSON data over the wire, it is very easy to start working with that data.

</Side.note>

This is quite a bit of work, right?

In Orcas we get support for JSON, URL parameters and non-SOAP XML. It also has Atlas-specific conventions such as the JavaScript proxy.

Support for calling WCF service from the client stack

Visual Studio 2008 has WCF AJAX support, meaning that the ScriptManager understands these types of services and new templates like the AJAX-enabled WCF service. The latter will automaticaly create the correct configuration and corresponding skeleton code.

Enabling a WCF service for AJAX is a decision you can make at deployment time. So, you can call into any regular WCF service from AJAX without making any changes to your implementation. You do need to make some changes, which vary based on your hosting scenario.

Let’s assume you have an IIS hosted WCF service. You need to edit the ServiceHost directive in the .svc file and specify a different ServiceHostFactory implementation, like so:

<%@ ServiceHost Service="CoolestWCFService" Factory="WebScriptServiceHostFactory" %>

Here WebScript actually means AJAX-enabled.

When you host the WCF service yourself, you should edit your configuration file to enable JSON support.

<system.serviceModel>

  <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />

  <services>

    <service name="AjaxService">

      <endpoint address="" behaviorConfiguration="AjaxBehavior"

        binding="webHttpBinding" contract="IAjaxService" />

    </service>

  </services>

  <behaviors>

    <endpointBehaviors>

      <behavior name="AjaxBehavior">

        <enableWebScript />

      </behavior>

    </endpointBehaviors>

  </behaviors>

</system.serviceModel>

Note how you only need to add an endpoint behavior for enabling WebScript. This makes WCF do the same thing as ASMX web services: it can generate a JavaScript proxy when you visit the URL http://…/CoolestWCFService.svc/js. BTW, the WebScriptServiceHost automatically adds this behavior to any endpoint that has a WebMessageEncodingBindingElement in its Binding element list, but does not have the WebHttp behavior defined. If you are interested in a little more on hosting, check here (a bit dated, but still pretty much ok).

So, why would you switch to WCF services instead of ASMX services?

  1. The separation of contract and binding:
    Because the service contract and the binding are separated it will line you up better for future versions of encoding or . You will only need to change the configuration file to hook up e.g. some JSON version 2 (which might become reality to fix the recent security vulnerabilities in JSON v1). Or, you can add an application layer to expose the same service simultaneously as an AJAX and a SOAP service.
  2. The cool features of WCF:
    How are you going to protect your ASMX service from Denial of Service (DoS) attacks? In WCF you can protect your service with quotas, throttles and timeouts. There are more manageability options, such as logging, tracing and a whole bunch of performance counters. Think about the extra hosting options (e.g. self-hosted) for WCF services.
    Also, Workflow Services in .NET 3.5 allow you to put a workflow inside a service which is behind an AJAX-enabled page. Compared to ASMX you could get performance gains as much as 4 times for large messages (rough estimate and preliminary results). And you get to use the HTTP programming model, such as POX and returning binary data.
  3. The DataContract data model:
    Going forward from .NET 3.0 the DataContract way of serializing is the preferred way. In 3.5 you may have noticed that Linq to SQL and ADO.NET Entities have built-in support for DataContract as well. The generated types for both Linq to SQL and ADO.NET Entities are [DataContract] types. Also, Linq to XML will have its XNode and derived types serialize to strings, so there is no problem to send them over the wire and use these in JavaScript. Furthermore, the DataContract is an opt-in model, so your type never gets serialized by accident. This is especially important, since you are sending the information to the browser client. The future directions of "Orcas+1" also indicate neat stuff to happen with the workflow data model and transformations (see this entry for a little more detail).
  4. The future: There has been no investment in new features for ASMX since .NET 2.0 or in Orcas. Will there be for the future?

Finally, here are some characteristics of the WCF AJAX architecture:

  • Operation names are in the URL. There are no SOAP actions. A special operation dispatcher makes this happen.
  • Parameters in URLs, because no message body is available for GET requests. Again, a special formatter will take care of that.
  • JSON parameters in URLs (Atlas-specific) allows for complex types to be passed from the client to the service.
Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s