views:

574

answers:

5

I am developing some client side javscript that is using some JSON web services on a different domain. I have read that some browsers do not allow cross-domain scripting and that I should create a proxy on my local server to serve the data.

Can someone please point me to a simple example of how to do this in ASP.Net?

+1  A: 

No browsers allow cross-domain scripting, and although w3c has left space for this in its recommendation on the xmlHTTPRequest-object, we still have to wait for some time to see it implemented in a secure way ...

roenving
IE8 (in beta) has an implementation for cross-domain requests... but again, you'll need to wait.
scunliffe
A: 

I'll give a pseudocode version for people seeking a general answer to the question.

SomeAjaxAbstraction.Request('proxyScript', {
    parameters: {
        address: 'http://somewhere.com/someapi?some=query'
    }
});

Then in proxyScript:

var address = GET['address'];
if(ValidUrl(address) && ConnectionAllowed(address)) {
    // Validating address and whitelisting services is an exercise to the reader
    var response = SomeHttpGetFunction(address);
    echo XssAndBadStuffFilter(response);
} else {
    // Handle errors
}
eyelidlessness
+2  A: 

You may be able to avoid a proxy by using a technique like JSONP. Assuming the web service you're talking to supports JSONP (for example, Flickr or Twitter both offer a JSONP API) or you have control over the data the web service sends back, you can send JSON data between domains using a library that features JSONP.

For example, in jQuery, you can make a remote JSON call:

jQuery.getJSON("http://www.someothersite.com/webservice?callback=?", function(result)
{
    doStuffWithResult(result);
});

Because the call is to another domain, jQuery automatically uses some trickery to make a cross domain call. jQuery will automatically replace the ? in the url with a callback function name that the web service can use to format the JSON data being returned.

If you're the one controlling the web service, you can handle the JSONP request by getting the request parameter called "callback" which will be set to the callback function name you need to use. The callback function takes one parameter, which is the JSON data you want to send back. So, if the callback parameter is set to "jsonp2342342", you'll want the web service to respond like this:

jsonp2342342({key: value, key2: value});

If the web service you're using already supports JSONP, you won't have to worry about doing the formatting yourself.

Matt Ephraim
+2  A: 

Generally speaking, the proxy runs on your web server - most likely IIS in your case - and 'relays' the requests to another server on a different domain.

Here's an example of one implemented in C# .NET

Fast, Streaming AJAX proxy

neonski
+1  A: 

You can write a simple .NET page to retrieve the remote page and display it on your site:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;

namespace Proxy
{
    public partial class _Proxy : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string proxyURL = string.Empty;
            try
            {
                proxyURL = HttpUtility.UrlDecode(Request.QueryString["u"].ToString());
            }
            catch { }

            if (proxyURL != string.Empty)
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(proxyURL);
                request.Method = "GET";
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                if (response.StatusCode.ToString().ToLower() == "ok")
                {
                    string contentType = response.ContentType;
                    Stream content = response.GetResponseStream();
                    StreamReader contentReader = new StreamReader(content);
                    Response.ContentType = contentType;
                    Response.Write(contentReader.ReadToEnd());
                }
            }
        }
    }
}

See my post about it: http://www.johnchapman.name/aspnet-proxy-page-cross-domain-requests-from-ajax-and-javascript/

chapmanjw