Pages

Monday, July 16, 2012

Expose .asmx Web Service to Third Party Clients consuming via Jquery Ajax

Imagine the Following Scenario:

1. http://domain1.com/webservice.asmx
    A .asmx WebService
 
2. http://domain2.com/client.html
    A Client consuming that WebService using Jquery Ajax

STEP 1

PROBLEM
This is a Cross-Domain Request and violates the Same origin Policy.
(which is a security concept for a number of browser-side programming languages)

SOLUTION
A work around is to use JSONP to make the Client Request.
IBM has a Great Article describing This.
Jquery Ajax is described here


STEP 2

PROBLEM
JSONP loads Javascript using <script src=""> element.
In ASP:net  Script files loaded via an HTML <script src=""> element within a browser can only be retrieved via HTTP GET verb requests.
By default ASP.NET  web services layer does not allow web methods to be invoked via the HTTP GET verb.

SOLUTION
To make an ASP.NET AJAX web-method callable via HTTP GET-access, a developer must explicitly attribute each method using ASP.NET's ScriptMethod attribute (and set the UseHttpGet property to true)
[ScriptMethod(UseHttpGet=true)]
Article 1

STEP 3

PROBLEM
T
he <script> element simply doesn't add content type "application/json; charset=utf-8"  to the request. Yet our JSON WebService is expecting this in the Header of the Request.

SOLUTION


Use a asp.net HTTPModule to filter all requests to the .asmx Webservice and Manually append the correct content type to the Request Header.
Article 1
Article 2


EXAMPLE CODE
Download
1. .asmx Web Service with HTTPModule
2. Jquery Ajax Client 

Setup

Set them both up as Websites in IIS or Apache
with the Client running on default port 80                 http://localhost/jquery-CrossDomainCall-Test.html
and the .asmx Service running on Port 83                http://localhost:83/Service4.asmx
Note you will also need to enable .Net4 for the .asmx Service Website



Same Origin Request
If the client is on the Same Domain as the Web Service
Then we can instead use simple $Jquery.Ajax()
as described in this Great Article

No comments:

Post a Comment