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)
{
response.Clear();

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

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

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

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

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

default:
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>");
response.Write("</body></html>");

response.End();
}


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.


 


No comments:

Post a Comment