Simple proxy to bypass cors

CORS is a pain in the ass, all works great with chrome and firefox,but, as often, internet explorer doesn’t (it should work with ie 10 but you know…)

So the proxy solution is simple and works, even if I would prefer a full html/jquery solution.

To create a proxy for the get requests it’s simple.

Create an asp.net webform, add this in the pageload.


protected void Page_Load(object sender, EventArgs e)
{
 string serviceUrl = HttpContext.Current.Request.Params["service"];
 if (string.IsNullOrEmpty(serviceUrl))
 {
  return;
 }

 string query = string.Empty;
 int firstParamIndex = HttpContext.Current.Request.Url.Query.IndexOf('&');

 if (firstParamIndex > -1)
 {
  query = HttpContext.Current.Request.Url.Query.Remove(0,firstParamIndex+1);
 }

 string service = serviceUrl + "?" + query;

 WebClient client = new WebClient();

 foreach (string headerKey in HttpContext.Current.Request.Headers.Keys)
 {
  try
  {
    client.Headers[headerKey] = HttpContext.Current.Request.Headers[headerKey];
  }
  catch (Exception ex)
  {
    System.Diagnostics.Debug.WriteLine(ex.Message);
  }
 }

 // specify encoding : avoid special characters to be unrecognized.
 client.Encoding = Encoding.UTF8;
 string resultString = client.DownloadString(service);

 // carriage returns.
 Response.Write(resultString.Replace(@"\u000d\u000d", "<br/>"));
}

you can restrict some headers this way


protected void Page_Load(object sender, EventArgs e)
{
 string[] allowedHeaders =
 {
  "x-headers1",
  "x-headers2",
  "x-headers3"
 };

 string serviceUrl = HttpContext.Current.Request.Params["service"];
 if (string.IsNullOrEmpty(serviceUrl))
 {
  return;
 }

 string query = string.Empty;
 int firstParamIndex = HttpContext.Current.Request.Url.Query.IndexOf('&');

 if (firstParamIndex > -1)
 {
 query = HttpContext.Current.Request.Url.Query.Remove(0,firstParamIndex+1);
 }

 string service = serviceUrl + "?" + query;

 WebClient client = new WebClient();

 foreach (string headerKey in HttpContext.Current.Request.Headers.Keys)
 {
  if (allowedHeaders.Contains(headerKey))
  {
   try
   {
     client.Headers[headerKey] = HttpContext.Current.Request.Headers[headerKey];
   }
   catch (Exception ex)
   {
     System.Diagnostics.Debug.WriteLine(ex.Message);
   }
  }
 }

 // specify encoding : avoid special characters to be unrecognized.
 client.Encoding = Encoding.UTF8;
 string resultString = client.DownloadString(service);

 // carriage returns.
 Response.Write(resultString.Replace(@"\u000d\u000d", "<br/>"));
}

In your web client :


if (jQuery.support.ajax)
{
 $.ajax({
 headers:
 {
  "x-headers1": "header value 1",
  "x-headers2": "header value 2",
  "x-headers3": "header value 3"
 },
 contentType: "application/json; charset=utf-8",
 dataType: "json",
 url: "youpage.aspx?service=yourservicecompleteurl",
 data:
 {
  param1: value1,
  param2: value2
 },
 success: function (msg)
 {
  callback(msg);
 },
 error: function (errormsg)
 {
  if (errorCallback != 'undefined')
  {
  errorCallback(errormsg);
  }
 }
 });
 }
 else
 {
  alert('You browser doesnt support ajax.');
 }

I could use a webservice, but it would force me to do POST requests and I doesn’t want to make changes in my jscripts.

[Update 20120405 ]

Here is the full proxy code, which handles both get and post requests :


using System;
using System.Linq;
using System.Web;
using System.Text;
using System.Net;
using System.IO;

namespace yournamespace
{
 public partial class Proxy : System.Web.UI.Page
{
/// <summary>
/// Definition of the headers to transfer.
/// </summary>
private static string[] requiredHeaders =
{
"x-your-required-header-1",
"x-your-required-header-2",
"x-your-required-header-3",
"Content-type"
};

/// <summary>
/// Overrides the onload event to handle get and post requests.
/// </summary>
/// <param name="e"></param>
protected override void OnLoad(EventArgs e)
{
bool isPost = string.Equals(HttpContext.Current.Request.HttpMethod, "POST", StringComparison.OrdinalIgnoreCase);
string serviceUrl = HttpContext.Current.Request.Params["service"];
if (string.IsNullOrEmpty(serviceUrl))
{
return;
}

string service = serviceUrl + (isPost ? "" : "?" + GetQuery());
WebClient client = new WebClient();

// copy required headers
foreach (string headerKey in HttpContext.Current.Request.Headers.Keys)
{
if (requiredHeaders.Contains(headerKey))
{
try
{
client.Headers[headerKey] = HttpContext.Current.Request.Headers[headerKey];
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
}
}

// specify encoding : avoid special characters to be unrecognized.
client.Encoding = Encoding.UTF8;
string resultString = string.Empty;
try
{
if (isPost)
{
client.Headers.Add(HttpRequestHeader.ContentType, "application/json");

using (MemoryStream str = new MemoryStream())
{
HttpContext.Current.Request.InputStream.CopyTo(str);
byte[] result = client.UploadData(service, str.ToArray());
resultString += Encoding.UTF8.GetString(result);
}
}
else // GET
{
resultString = client.DownloadString(service);
}
}
catch (WebException wex)
{
System.Diagnostics.Debug.Write(wex);
resultString = "<h1>An error occured : " + wex.Message + "</h1>";
resultString += "<br/>Status : " + wex.Status;
if (wex.Status == WebExceptionStatus.ProtocolError)
{
HttpWebResponse httpResponse = wex.Response as HttpWebResponse;
if (httpResponse != null)
{
resultString += string.Format("<br/>Status Code : {0}", httpResponse.StatusCode);
resultString += string.Format("<br/>Status Description : {0}", httpResponse.StatusDescription);
}
}
resultString += "<br/><br/>Requested service : " + service;
}
catch (Exception ex)
{
System.Diagnostics.Debug.Write(ex);
resultString = "<h1>An error occured : " + ex.Message + "</h1>";
resultString = ex.GetFullMessage();
resultString += "<br/><br/>requested service : " + service;
}
finally
{
client.Dispose();
}
Response.Clear();
Response.Write(resultString);
}

/// <summary>
/// Gets the query part.
/// </summary>
/// <returns></returns>
private static string GetQuery()
{
string query = string.Empty;
int firstParamIndex = HttpContext.Current.Request.Url.Query.IndexOf('&');
if (firstParamIndex > -1)
{
query = HttpContext.Current.Request.Url.Query.Remove(0, firstParamIndex + 1);
}

return query;
}
}
}

Incoming search terms:

  • cors proxy
  • bypass cors jquery
  • corsproxy
  • how to bypass cors
  • bypass cors
  • CORS and proxy
  • catch (webexception wex) sharepoint
  • bypass chrome cors
  • use proxy to support browser that doesnt support cors
  • ajax cors request behind client proxy