Reading JSON through JQuery from Cross Domain ASP.NET Web Service

Recently I had an issue with JQuery and accessing JSON from a cross domain ASP.NET Web Service. After much googling, I stumbled upon many articles that provided no fix that would solve the issue.

Every sample I found was some derivative of the following code:

Nearly every post pointing out that the contentType argument was the issue but it still didn’t work when I included it. There were posts that said you can’t use GET and had to use POST. There might be valid security issues with not using GET but that’s another topic of discussion. in the case of an open web service where you’re providing raw data to be consumed, a GET should suffice just fine.

To support GET, you need to add the following attribute tags to your asmx.cs:
[sourcecode language=”csharp”][WebMethod(), ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)][/sourcecode]

This will cause ASP.NET to automatically serialize the returned data to JSON without requiring you to do it manually in code. There are no issues when making the call locally either. The second you go cross domain, the call fails.

A few articles mention JSONP (JSON with Padding) which is supposed to provide a workaround for the Same Origin Policy in JavaScript. Once I implemented the JSONP, the entire function

 


There are no comments.

Leave a Reply