Custom 404 redirect for a site with URL rewriting
In my site, I have used IIS7's URL rewrite module to redirect URLs like http://mysite.com/File.aspx?Name=SomeName into http://mysite.com/SomeName.
It appears that IIS7 has created a corresponding rule check, so that any URL of the sort http://mysite.com/SomeURL is redirected to File.aspx. This is fine in most cases, when the URL is correctly rewritten.
The problem is that in some cases, the file no longer exists - http://mysite.com/SomeName2 will still get redirected to http://mysite.com/File.aspx?Name=SomeName2.
I want to show a custom 404 error page for this URL - how do I trigger the 404 error in global.asax (I have set application error logging and handling in global.asax)? The below code doesn't work.
Response.Status = "404 Not Found"
Response.AddHeader("Location", "http://mysite.com/Invalid开发者_运维技巧-File.aspx?" & Request.QueryString.ToString)
It just shows the ugly default IIS 404 error page. Adding a customerror in web.config doesn't help.
Thanks for your help!
When setting a status code you need to prevent IIS taking over based on your new error code, make sure to set Response.TrySkipIisCustomErrors
like this:
Response.TrySkipIisCustomErrors = true;
Response.StatusCode = (int)HttpStatusCode.NotFound;
Response.AddHeader("Location", "http://mysite.com/Invalid-File.aspx?" & Request.QueryString.ToString)
Did you try setting the 404 error page in the IIS admin equal to what you're specifying in the web.config? I wonder if .net isn't jumping into the pipeline at the right time.
you could potentially use the Application_Error method and then do a response.redirect to the required page with the correct status code
精彩评论