HowTo: Cross Domain Ajax with JSONP and ASP.NET

ajax

Actually it isn´t possible to send Ajax Requests to addresses which are reachable at the same domain like the site where the script is executed.The reason for this is the Same Origin Policy in JavaScript. There it is given, that the port, the protocol and the domain have to be equal to start requests. This is save but unfortunately not practical.

But there is a Trick. Right?

Yes! There are a lot of different possibilities to avoid the problem. Enter “Cross Domain Ajax” into the searching engine and you will have a wide pool of solutions. I almost spend half a day to take a look on all the different websites. For example it is possible to use a Proxy or Flash/Silverlight and so on. For me the best solution was JSONP.

What´s JSOPN?

JSOPN is the short form of  “žJSON with padding”.

The Idea behind it is as simple as clever. It works by using a security hole of the implementation of the Same Origin Policy of the Browser. It isn´t possible to start requests to other domains but you are allowed to include JavaScript Files from other Domains and while doing this you can easily import your own files. The disadvantage is that it is only possible to send data via GET and not via POST. Who plans to send more data, has to use another trick otherwise you need to compress your data. JQuery makes the implementation at this point easy as usual and help us with the adequate methods:

And this is how it looks like:

At the Client:
  1. $.ajax({
  2. dataType: ‘jsonp’,
  3. jsonp: ‘jsonp_callback’,
  4. url: ‘http://localhost:56761/TestService.ashx’,
  5. success: function (j) {
  6. alert(j.response);
  7. },
  8. });

The only difference to the usual jQuery Request is the line: “žjsonp: “˜jsonp_callback´”. This line includes the GET name of the parameter where jQuery transmit the name of the Callback function to the server.

jQuery works like this:

  1. A <script> tag is created which points to the chosen address. In the process a random number is transmitted as a parameter (that´s the name of the calback function).
  2. The server produces a JavaScript file for response, which opens a function with the random number and pass it as a JSON file.
  3. The browser integrates the script and accomplishes the whole thing. jQuery now submits us the file to the “success” Event.
And at the Server:
  1. string response = context.Request.Params["jsonp_callback"];
  2. response += “({\”response\”:\”" + context.Session["RequestCounter"]  + ” requests startet\”});”;
  3. context.Response.Write(response);

http://code-inside.de/blog/wp-content/uploads/image_thumb67.png

For this example I used a Generic Handler (.ashx). But you could also use a WCF service. The example consists of two projects. A clientproject “CrossDomainAjax” and a serviceproject “SourceDomain”. To start the demo press with the right mousebutton on the name of the Project -> debug -> Start new instance

Both projects should be started now. After this you should see a javascipt alert with an “1″ in your browser window. With this example I also tried to find out if it´s possible to access the session of the server, and it works. After every rebuild of the page the value increase by one.

I know it´s not a really exiting example but I hope you are able to forgive me about this.

Here you can find the demo code. Have Fun :)

Read more

HowTo: Introduction in to MetaWebLog API

This Blogspot is based on Scott Hanselmans “WeeklySourceCode”, where MetaWebLog API was the subject of today. In the Blogspot he relates that MS use the Windows Live Writer also to administrate their own websites. The tool is absolutely practical and it works with MetaWebLog API. With this tool it´s possible to create “CMS” Content with […]

Read more

Windows 7 RC Training Kit for Developer

Microsoft released the Training Kit for developer yesterday. It contains presentations, Hands on Labs and democode for the new Windows 7 APIs. The Traing Kit is directed towards to C++ developers, but Microsoft offers Wrapper classen for .NET. Topics: Taskbar Libraries Multi Touch Sensors and Location Ribbon Trigger Start Services, Instrumentation and ETW Application Compatability […]

Read more

Visual Studio 2010 & .NET Framework 4 Training Kit – May Preview

Microsoft released a preview Training Kit for .NET 4.0 & VS 2010: Download. It includes 28 presentations, 13 demos & 16 Hands-on Labs.   Overview The Visual Studio 2010 and .NET Framework 4 Training Kit includes presentations, hands-on labs, and demos. This content is designed to help you learn how to utilize the Visual Studio […]

Read more

Inside Microsoft’s home of the future

Microsoft shows in a Video how the “home of the future” might look like. Some photos of this house could be found here. Speak recognition & “NUI“s are “key features” in this house.  

Read more

Free eBook: Practical .NET Unit Testing

Nice intro to unit testing (& mocking) with .NET: – Practical .NET Unit Testing

Read more

Free eBook: Testing Chapter from Beginning ASP.NET MVC

Just found an interesting eBook: – Free Chapter of Beginning ASP.NET MVC 1.0 – Testing ASP.NET MVC Applications (Blogpost)

Read more

HowTo: Create RSS Feeds with Linq to XML / XLinq

It´s very easy to create an RSS using Linq to XML. In my sample I create a ASP.NET page, which offers a RSS Feed. We add also a meta tag so that users can find our RSS Feed.     Project structure: To let the user know that we offer a RSS Feed we create […]

Read more

HowTo: Tweet with C#

Twitter is the internet Microblogging Service – this is my acc BTW. Twitter has an API since the beginning (and IMHO is this one big reason why twitter is so successful). The Twitter API is REST based and so you can easily create Twitter-Clients with .NET. If you don´t want to create the HTTP basic […]

Read more

Free eBooks: ADO.NET Entity Framework, Powershell & C#

Just found 3 eBooks: – ADO.NET Entity Framework: Learning Guide  – Effective Windows Powershell – Illustrated C# 2008

Read more

Recent Posts

  • image1929-570x143_thumb.png
    Create and validate own Json-Web-Tokens (JWTs)

    If you are interested in web authentication you probably have heard about JSON Web tokens (JWT). What is a JWT? Maybe I’m not using the correct security termination but however: JWTs are used to exchange claims between two systems. For example: You want to log on to a service (like Facebook, Twitter, etc.) and want […]

  • Micro-Optimization: how to shrink or „embed“ pictures

      I’m currently working on the “CodeInside Dashboard” and since the page structure isn’t that difficult it should be possible to fulfill all of Google Pagespeed or Yahoos YSlow recommendations. One of the rules was to optimize the 4 PNGs that are embedded on the page.   Before – without optimization: Below you can see […]

  • image1979-570x194.png
    Move to Windows Azure – VMs, Word Press Migration, DNS changes

    Since mid January this blogs runs on a WordPress installation in an Azure VM. Because I always thought that the subject is quite complicated this blogpost offers a view behind the scenes. Why this move? So far this blog (both German and English Version) runs on a hoster somewhere in Germany. The main problem with this […]

  • Windows Azure Active Directory – CRUD for users and groups

      Windows Azure Active Directory? If you are not informed about the subject I recommend you to have a look on this Azure Info site. Which resources are there? The Azure AD contains the following entities: - Users - Groups - Contacts - Roles Access to the directory or on the “directory graph” Although the […]

  • Introduction into SignalR 2.0 & Azure Website Websockets

      SignalR is an Open Source Framework for Real Time WebApps. The main problem with Real-Time in the web is the canal between Browser and Server. If you never had to deal with SignalR and this problem before here is a brief introduction:   The problem Traditionally the browser initiates the request to the server […]

Support us