I use ASP.Net URL Routing for SEO and when I run into a routename that is bad in (i.e. /Games/{RouteName}) I want to pass it to my 404 page for handeling. I check the DB to make sure {RouteName} is a valid name for a game. If the RouteName is valid I want to continue processing as normal but if the DB comes back and does not find a corisponding RouteName I would like to some how have the server act as if a truly bad URL was entered. How can I best accomplish this?
I would suggest throwing a 404 error inside your logic that determines it is not valid, e.g.
if (!<validRouteName>) {
return new HttpStatusCodeResult(404, "Game not found.");
}
Doing a bit of messing around in IIS I have figure this out. As endyourif suggested I need to throw a 404 resposne in my code behind, which was done by Response.StatusCode = 404; I also had to configure IIS's Error Pages for the 404 to point to my 404.aspx page.
Related
Okay, here's the deal:
I have an aspx page that looks like mysite.com/UnitDetails.aspx?UnitID=123
Right now I've setup my routing to be able to take in something like mysite.com/My/Path/123 and redirect it to UnitDetails.aspx. This works great.
However, what I'd like to be able to also do is redirect the user to the clean url if they type in the aspx page. For example, if you have mysite.com/UnitDetails.aspx?UnitID=123 bookmarked, I'd like it to show up as mysite.com/My/Path/123.
How can I accomplish this? Here's what I have right now in my routing:
RouteTable.Routes.MapPageRoute("unit_details", "{area}/{property}/{unit_id}", "~/UnitDetails.aspx")
Okay, I figured it out!
Just needed to add this into my UnitDetails.aspx code behind in the Page_Load:
//issue a 301 if legacy route requested to boost SEO
if (Request.Url.AbsolutePath.Contains("UnitDetails.aspx"))
{
var unit = BeachGuide.Models.Unit.GetById(Convert.ToInt32(Request.Params["UnitID"]));
Response.RedirectPermanent(unit.relative_url);
}
So now if they request the new url, they won't get caught in an infinite loop. If they request the old url, we have a base case that redirects them to the new url via a 301 redirect. This will help search engines know to use the new route as the canonical url.
Is there a way to redirect the users to the homepage whenever the user enters a wrong url?
Let's say app.php/Contact triggers a 404 error and I would like all 404 errors to be redirected to the homepage?
I am pretty sure I read that somewhere at a time, but can't find it anymore. I think it was a else statement in the config file?
You should extend ExceptionController and redefine showAction() with the logic you need.
Simply as:
if (404 === $exception->getStatusCode()) {
//do your logic
}
Use an .htaccess file and add the following line:
ErrorDocument 404 /home.php
I have some routes in my ASP.NET MVC application that handle redirecting of old urls. The URL I'm redirecting is:
contentSpanishContentList.aspx
Here's the route:
routes.MapRoute("RedirectLegacyContent1",
"content{contentUri}.aspx",
new { controller = "Redirect", action = "Content", contentUri = string.Empty, contentId = 0 });
The problem is it comes up as not found. I figured out that the problem is (in bold) contentSpanish*Content*List.aspx. What should I do to make this route work with this case?
Two solutions
Rename your pages to not include the same constant string (in your case it's the word content).
Write a custom route that's able to parse your requests - all you'll have to override is the GetRouteData method. And if you're planning to only use this route for incoming requests (not generating any URLs in your views to point to any of these pages ie. using Url.Action or Html.ActionLink) then the easiest way would be to generate something like a RegExRoute which would be easy to write and also easy to resolve these kind of requests.
The fist one is simple, the second is universal.
Use Fiddler to look at what's happening. Is the 404 happening on the first request? Or is it happening after the redirect?
Install the RouteDebugger package and see what it tells you.
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
So, from here...
In ASP.NET, you have a choice about how to respond to that - it's in the web.config as CustomErrors. Turn that on, then redirect to a fancy 404 page (maybe you already do). The fancy 404 page, then, could be checking the requested querystring (which gets passed over to the custom error page as yet another querystring) to see if it's a valid redirect, lives in your database, etc. Just do a Response.Redirect() from there.
Then schooner writes:
Thanks, we do have a 404 now but we would prefer this not to be detected as a 404 in the process. We would like ot handle it directly and seperately if possible.
..and I'd like to know just how bad a practice this is. I don't expect to put my "pretty" URLs on the internet (just business cards) and I have a sample of 404-redirecting-to-a-helpful-site code working, but I don't want to get to production and have an issue with a browser that takes the initial 404 too seriously. Can anyone help me understand more about why I wouldn't want to use customErrors / 404 to flow users to the page they actually wanted?
The main problem with using customeErrors as your 404 error handler is that every time customErrors picks up an errored request rather than throwing a 404 error back to your browser and letting your browser know there was a bad request, it instead returns a 302 which indicates that a page has been relocated to whatever your customErrors page is. This isn't bad for most users because they don't know or even notice the difference, the problem comes from the fact that web crawlers DO know the difference and the status code they receive directly affects how their indexing works.
Consider the scenario where you have a page at http://mysite.com/MyAwesomePageAboutStuff.aspx for some period of time and then one day you decide you no longer need it and delete the file. If Google or some other crawler has already indexed that URL and goes back to it after you delete it the crawler will get a 302 status code instead of a 404 error and because of this status code the crawler will update the page's url to point to your error page rather deleting the non-existent link. Now, whenever someone finds that url by way of a search engine they'll end up at your error page.
It's not really a huge issue, but you can definitely see the headaches this can create for your users in the long run.
Look here for some corroborating data.
I created a vanity url system using the 404 as the handler. There's no need for a 302 on my side as the 404 dynamically loads the content and returns that. I am fully able to handle any and all POST / GET and SERVER data.
Works great. If you are interested TarantulaHawk is up on SourceForge.