Sunday, May 9, 2010

ASP.NET 4: Could’ve used that…

At SQL Sentry HQ we all tend to wear a few different hats. It’s important to make sure every base is covered regardless of who is or is not available.

That said, besides doing customer support and a portion of product development, I am also generally responsible for development work on internal systems and a good portion of our web site. To be specific in the context of this post, I do a fair amount of work on our forum (forum.sqlsentry.net) and our customer portal (www.sqlsentry.net/portal).

As with any web site, pages move, URIs change over time, and browsers have to be redirected to avoid the dreaded 404.

HTTP 1.1 has supported the permanent redirect status (301) with the location header for some time. This is a redirect so that (if the browser understands it) the next time the old URI is encountered the round trip to the server is avoided saving some resources on both sides and in-between.

Prior to ASP.NET 4 if you wanted to do this you had to set the location header and status on the request like below:

//Response status
Response.Status = "301 Moved Permanently";
//New location header
Response.AddHeader("Location","http://the.new.location");

Then you end the response etc. and this works out fine. It’s just a pain to have to include this in some utility class, and it’s really not that intuitive either. You have to know that you want to do exactly this. It’s not something that you can happen across by studying the Response object’s members in general.

Well, today I was just doing some personal skills maintenance, and I saw that in ASP.NET 4 they’ve added a new Response method called RedirectPermanent. It issues the 301 response as outlined above instead of 302 (temporarily moved) which is sent by the regular Redirect method.

It’s simple to use, it’s just one line as below:

//Redirect permanently
Response.RedirectPermanent(http://the.new.location);

You can use a relative path in there too even though the RFC technically doesn’t support it. You can also specify to end the response immediately as a second parameter.

Anyway, it doesn’t solve world peace and it’s not even a compelling reason to go out and rewrite a bunch of code, but like I said in the title, I could’ve used that! :o)

Until next time,

-JRH

No comments:

Post a Comment