Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
492 views
in Technique[技术] by (71.8m points)

asp.net - Redirecting default.aspx to root virtual directory

I have a simple ASP.NET 3.5 application running under IIS7 under a virtual directory. So the URL of my app is like http://example.com/app. I want to 301-redirect the request to example.com/app/default.aspx to example.com/app for better SEO. I have to do this redirect through code only, not by any IIS settings. I am unable to do so via code mentioned in this article:

http://www.4guysfromrolla.com/articles/072810-1.aspx

The code:

if (request.RawUrl.Equals("/default.aspx"))
{
newUrl = string.Format("{0}://{1}{2}",
                 request.Url.Scheme,
                 request.Url.Authority,
                 request.RawUrl.Remove(request.RawUrl.LastIndexOf("/default.aspx", StringComparison.OrdinalIgnoreCase)));

               context.Response.Status = "301 moved permanently";
               context.Response.AddHeader("Location", newUrl);
}

seems to go into an infinite loop when the application is under a virtual directory. the request.RawUrl property always returns "/default.aspx" even after a 301 redirect causing the infinite loop. How can I fix this issue?

thanks,

Asif

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The above code will work fine as long as you dont have a sub-directory. AFAIK, its a bug in ASP.NET: the Request.RawUrl should NOT contain "/default.aspx" when the URL does not have that extension. I have tested your code and it works fine without a sub directory, but if default.aspx is under a directory, the Request.RawUrl object fails to get rid of default.aspx and hence the infinite loop.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...