I thought it should be a simple straight-forward matter but after struggling with it for too much time I'm gonna have to seek for help.
What I need is to redirect all requests for my web application that match the following pattern - "^(http://[^/]+/blogs/[^/.]+)/?$
" to the path of "$1/Default.aspx
".
(Using English rather than Regex: http://myapp/blogs/randomdirthatdoesntexist
-> http://myapp/blogs/randomdirthatdoesntexist/default.aspx
)
The sub-directories in "blogs" do not physically exist, inst开发者_开发技巧ead a 3rd party product deals with the requests to randomdir/Default.aspx", but when you go to "randomdir/" you get 404 not found, which is what I'm trying to fix.
I tried to use global.asax
and also HttpHandler
, but I couldn't get either of them to fire up on the requests to those 404 paths.
So, in short, what should I do to redirect paths of non-existing directories?
Thanks.
I accomplished something similar to this by setting the Error Page for 404s in IIS to a page you create. This page is able to access the page which is being requested, and perform some additional logic. So the 404 for randomdirthatdoesntexist/ still happens, but the 404 handler notices this and redirects to randomdirthatdoesntexist/default.aspx.
I dug out my old code and tweaked it a little to do what you need in an over-simplified fashion, but I don't have IIS6 anywhere to test:
protected void Page_Load(object sender, EventArgs e)
{
String sQueryString = Request.RawUrl.Substring(Request.FilePath.Length);
Regex rx = new Regex(@"^\?(?<errorcode>\d+);(?<args>.*)$", RegexOptions.ExplicitCapture | RegexOptions.Compiled);
Match m = rx.Match(sQueryString);
if (m.Success)
{
if (m.Groups["errorcode"].Value == "404")
{
String sArgs = m.Groups["args"].Value;
Uri requestedUri = new Uri(sArgs);
// You can now check the value of uri and perform redirection...
if (requestedUri.ToString().EndsWith("/"))
{
Response.Redirect(requestedUri + "Default.aspx")
}
}
}
Response.StatusCode = 404;
}
Use a Custom HttpModule, or Http Handler, which sits in early enough in the Http Request pipeline to direct your requests appropriately before any possible 404 response is determined.
See my own SO Q&A; Server.Transfer or Server.RewritePath for more details.
精彩评论