RSS Feed Proxy in C# .NET

Monday, January 25, 2010 04:18 PM

A quick and dirty example of how to make a feed proxy in C#/.NET for that cross site request browser security issue on the client side.

You would call it via a url like this ...

http://mydomain.com/Proxy.ashx?u=http://feeds.heatxsink.com/heatxsink/atom

filename: Proxy.ashx

<%@ WebHandler Language="C#" CodeBehind="Proxy.ashx.cs" Class="FeedProxy.Proxy" %>

filename: Proxy.ashx.cs

using System;
using System.Web;
using System.Net;
using System.IO;

namespace FeedProxy
{
    public class Proxy : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            string url = context.Request.Params["u"];
            if(!string.IsNullOrEmpty(url))
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "GET";
                request.KeepAlive = true;
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                string responseBody = string.Empty;
                using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                {
                    responseBody = reader.ReadToEnd();
                }

                context.Response.ContentType = response.ContentType;
                context.Response.Write(responseBody);
            }
            else
            {
                context.Response.ContentType = "text/html";
                string message = string.Format("You must supply a 'url' query parameter.");
                context.Response.Write(message);
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}