John Chapman

ASP.NET Proxy Page – Used for Cross Domain Requests from AJAX and JavaScript

Share on TwitterShare on LinkedInShare on TumblrSubmit to StumbleUponSave on DeliciousDigg ThisSubmit to reddit

One of the pain points with developing AJAX, JavaScript, JQuery, and other client-side behaviors is that JavaScript doesn’t allow for cross domain request for pulling content. For example, JavaScript code on www.sharepointjohn.com could not pull content or data from www.bing.com.

One way to overcome this issue is by using a server-side proxy on the site running the JavaScript code. There is already are well documented PHP solutions on the web, however I couldn’t find very many .NET-based solutions. This simple C# code takes the URL passed to it through the URL encoded query string, retrieves the content of the URL and outputs it as if it were content on the site.

Proxy.aspx.cs
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());
                }
            }
        }
    }
}
Proxy.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Proxy.aspx.cs" Inherits="Proxy._Proxy" %>

The Proxy.aspx page is simply blank except for the Page tag. When passing the URL to the query string, it is important that it is URL encoded. This helps to prevent query strings of the remote site URL from interfering with the Proxy page.

Example Usage
http://www.yoursite.com/proxy.aspx?u=http%3a%2f%2fwww.google.com

ASP.NET Proxy Page Source

Happy coding!

Share on TwitterShare on LinkedInShare on TumblrSubmit to StumbleUponSave on DeliciousDigg ThisSubmit to reddit

John Chapman

Hello, I'm John Chapman. I am a SharePoint developer living in Mesa, Arizona. I develop solutions using ASP.NET, C#, jQuery, SQL, SharePoint, etc, and I thrive on the challenge of writing code to overcome the impossible, annoying, or otherwise difficult obstacles.

Website - Twitter - More Posts

19 Comments

  • Brilliantly simple solution, thanks! This will work wonders on our SharePoint intranet.

    • That is exactly what I use this for. I place the page in the LAYOUTS folder on the server to make it available to all the SP sites. I primarily use it for consuming RSS feeds across domains.

  • Well done. Good to see what’s possible.

  • But it doesn’t support POST.

    • In what scenario would you want to POST to this proxy page?

      • In case you are using a REST based service and don’t want to use the ugly GET? :-)

        • Your REST based service is very RESTful if it isn’t using GET for READING DATA.

          I can see that using a POST might be desirable to post to another server and make sure the Proxy follows any redirects for you.

  • After seeing this, http://www.experts-exchange.com/Q_26452332.htm, I can think of several situations where you might want to “POST” data to a remote web-service, and stick the results in a local page e.g.
    * Exchange rate conversion,
    * Stock price lookup,
    * delivery rate lookup.
    Personally I’d use Apache to Reverse Proxy the requests to the remote site, by adding the entries below to the httpd.conf, but there are plenty of equivalents for IIS, out there e.g. http://www.codeproject.com/KB/web-security/HTTPReverseProxy.aspx

    #— cut ‘n’ paste into you Apache httpd.conf —
    ProxyRequests Off

    Order deny,allow
    Allow from all

    ProxyPass /proxy http://www.some.webservice
    ProxyPassReverse /proxy http://www.some.webservice
    #—- Cut ends —

  • It is great to see what is possible!

  • Lovely and simple.

    I would very much to use this to set the src-attribute for an img, but it does not seem to work. Any ideas?

    • Can you explain the scenario a bit more? I’m not sure I see a correlation between this proxy solution to populating the src for an image.

      • John,

        I also have the requiremnt to proxy the SRC attribute of an image. The scenario is that a page reads the contents of an RSS feed (not my own) which resides on a different domain. The description tag of the RSS feed contains HTML mark-up included within it including an image.

        The image doesn’t currently display which i believe is due to the cross domain requests restriction. I would like to deliver the contents of the image via a proxy page in a similar to which you have described. I have based my attempt on your example provided but have been unable to get it to work.

  • You also need to copy the user-agent
    request.UserAgent = Request.UserAgent;

  • Hi!
    Thanks for the solution.
    I’m trying to use it for all requests (JS, Images, XML).
    Unfortunately it’s not working…For example, I’m trying to get an image using the proxy, so I use the following URL

    persacore.aspx?u=imagens/icones/tema_1/m/energia_m.png

    but the browser does not recognize it as an image. The Content Type is correct. Any ideas?

  • This is great thanks for sharing. With minor changes (accessing the Request object through context) I put this in an asynchronous HTTP handler for added efficiency and to support concurrency. I also updated a few things to support POST requests, as I do think this is worthwhile

    • Did you publish your modified code anywhere? What you added sounds exactly like what I thought was missing from this great post.

  • [...] 2010] Cross-Domain Proxy Page for Client-Side ScriptsFollowing my blog post about ASP.NET Proxy Pages for Client-Side Scripts I have created a SharePoint 2010 solution to add a proxy page to a SharePoint 2010 farm.CodePlex [...]

  • Thanks this proxy works great, except for images. Any image that is requested will not show in a browser due to “The image … cannot be displayed because it contains errors.” If I request an image and then request it via the proxy the first request returns fine and the 2nd returns this error message. Any suggestions? In case you are wondering I do have a valid case for requesting images – I’m performance testing mapping services via ajax

Leave a comment

John Chapman