Please navigate to the bottom of the page for Table of Contents

Tuesday, May 24, 2011

Return different HTTP response codes from Response.Redirect call in ASP.NET

As explained in my previous post, HttpResponse.Redirect performs the redirection by returning a 302 HTTP status code. A 302 response is generally indicative of “Moved Temporarily”. There is no default mechanism provided a return a different redirection code.

So how can we implement this. Short answer: using C# extension methods. Let’s look at some code below to understand this more clearly:

public static void Redirect(this HttpResponse response, int type, string url)

switch (type)
case 301:
response.StatusCode = (int)HttpStatusCode.MovedPermanently;
response.StatusDescription = "Moved Permanently";

case 302:
response.StatusCode = (int)HttpStatusCode.Found;
response.StatusDescription = "Found";

case 303:
response.StatusCode = (int)HttpStatusCode.SeeOther;
response.StatusDescription = "See Other";

case 304:
response.StatusCode = (int)HttpStatusCode.NotModified;
response.StatusDescription = "Not Modified";

case 307:
response.StatusCode = (int)HttpStatusCode.TemporaryRedirect;
response.StatusDescription = "Temporary Redirect";

goto case 302;

response.RedirectLocation = url;

response.ContentType = "text/html";
response.Write("<html><head><title>Object Moved</title></head><body>");
response.Write("<h2>Object moved to <a href=\"" + HttpUtility.HtmlAttributeEncode(url) + "\">here</a>.</h2>");


This code is elegant and simple (written by one very talented dev in my team). As you can see, we are building the response object in the function and are setting the correct status code and description for each specific case. We will discuss extension methods in detail in a later post.


1 comment: