web analytics
Press "Enter" to skip to content

The best way to hit WCF from JS, anywhere

Lars Fiedler

Those who have used the <ScriptManager> tag in an ASP.NET application know it to be one of ASP’s stronger features.  Using ServiceManager to generate AJAX code allows you to hit a WCF endpoint with minimal effort, and avoid nasty serialization issues.

But what if you want use WCF with a non-ASP application?

Most tutorials on the web focus on hitting WCF endpoints using AJAX libs such as jQuery.  While we love us some good ‘ol jQuery, we’ve often ran into nasty serialization errors when passing complex .NET types over the wire (Dictionary<int, Tuple<string, List<string>>> anyone?).

With <ScriptManager>, we can avoid these issues… but how can we make use of it outside ASP?

It’s actually as easy as 2 script tags!

  1. First include the MicrosoftAjax.js script, available for download here: http://ajax.aspnetcdn.com/ajax/3.5/MicrosoftAjax.js.
  2.  Then add a script tag pointing to yourService.svc/js. For example, for a service called UserService located at localhost/Services/UserService.svc, you would add the 2nd script as: <script src="localhost/Services/UserService.svc/js">

And that’s it!  You can now instantiate you’re service in JavaScript and call it’s methods.

Go forth and profit!

TypeScript/JSPM Bonus: 

Composable Analytics is a TypeScript/JSPM shop, so we use a TypeScript import statement and a JSPM path mapping to import the generated Ajax files.

Add 2 items in your JSPM config file.

First, tell JSPM to load the Microsoft Ajax file as a dependency to all Services URLs (in our case, all our services are under the /Services route, but you may have to add additional mappings if your services are in multiple places for some reason).

Now, provide an alias to import the services under:

Now, you can use a TypeScript import statement instead of script tags!  Check it out:

 

Lars Fiedler

Leave a Reply

Your email address will not be published. Required fields are marked *