Monday, October 13, 2008

code for 301 redirect pages with querystring using asp.net/c#

if you have a page with query string and you want to redirect it using asp.net please check the code below..

string c_absUri = Request.Url.DnsSafeHost;
string c_absPath = Request.Url.AbsolutePath;
//c_absPath = "/test.aspx";

string c_queryString = Request.QueryString.ToString().Length > 0 ? Request.QueryString.ToString() : String.Empty;


if (c_queryString.Contains("sname=")) //where sname is querystring
{

Int32 Countqry = 0;
Int32 qrylength = 0;
qrylength = c_queryString.Length;

Countqry = c_queryString.LastIndexOf("=");
Int32 rem = qrylength - Countqry;


string sname = c_queryString.Substring(Countqry + 1, rem - 1);

sname = sname.Replace("*", "&");
sname = sname.Replace("+", " ");




string newUrl = "http://www.abc.com" + c_absPath;

HttpContext context = HttpContext.Current;
context.Response.Status = "301 Moved Permanently";
context.Response.StatusCode = 301;
context.Response.AddHeader("Location", newUrl);



Response.Redirect(newUrl);
}

1 comment:

Sky said...

you know you can also put adsense on your error pages... just redirect to a page while application error in the global.asax

by the way nice info... thanx for sharing