Proxy ASP.NET HTTP Handler

From time to time you may need to have a simple proxy to overcome limitations introduced by your intranet security settings.
As a solution, you can create a simple HTTP handler that will route all requests through the server, like:
http://server/proxy.ashx?get=http://target.com/feed.xml
To have this running, just create a file called get.ashx in your www root, make sure you assign an AppPool running .NET 4.0+, and you are good to go:
<%@ WebHandler Language="C#" Class="ProxyHandler" %>
using System;
using System.IO;
using System.Net;
using System.Web;
public class ProxyHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        string urlString = context.Server.UrlDecode(context.Request["url"]);
        Uri url;
        if (!Uri.TryCreate(urlString, UriKind.Absolute, out url))
        {
            context.Response.Write("URL query parameter can not be parsed");
            return;
        }
        WebRequest webRequest = WebRequest.Create(url);
        using (WebResponse response = webRequest.GetResponse())
        using (Stream responseStream = response.GetResponseStream())
        using (context.Response.OutputStream)
        {
            context.Response.ContentType = context.Response.ContentType;
            responseStream.CopyTo(context.Response.OutputStream);
        }
    }
    public bool IsReusable
    {
        get { return true; }
    }
}


Comments