Url Forwarding for invalid routes? - c#

I'm upgrading an old asp.net webforms site. I want to make the URLs look nicer, so I'm using the routing system, like this:
void RegisterRoutes(RouteCollection routes)
{
routes.MapPageRoute("account settings",
"settings/account/",
"~/accountsettings.aspx");
}
This works fine. Urls like mydomain.com/settings/account/ look much nicer. However, the page can still be accessed using its physical location, as mydomain.com/accountsettings.aspx. I'd like to forward requests to these old form urls to my new urls.
What's the best way to do this? Is there a simple method I can use, as with RegisterRoutes?

I believe you'll need to let the routing engine know to ignore the route of the physical file using IgnoreRoute:
routes.IgnoreRoute("accountsettings.aspx");
Please double-check the syntax for IgnoreRoute as I don't remember if you'll need to include the relative path or just the file name.
Once you have that working you can trap the 404 that it will generate, possibly in the global error handler in global.asax, and redirect if that was the requested path. This blog posting has an example of how to trap a 404 in the global error handler: http://www.andornot.com/blog/post/Handling-404-errors-with-ASPNET.aspx
If this is a public site and you're concerned about SEO you may also want to consider specifying that it's a permanent redirect using http status code 301. This will tell Google and other search engines that the old page now exists at the new location and you won't lose the value from that page.
Hope that helps!

Related

url routing webforms conflict

Im just getting into Global.asax and the way to do url routing in WebForms. Here Im having a bit of a conflict with my default.aspx and my other files.
I want all my files to have the friendly url ie. mysite.com/welcome/ etc and Im achieving this by doing:
routes.MapPageRoute("root_pages", "{file}/{*action}", "~/{file}.aspx");
by this I can write mysite.com/welcome.aspx into mysite.com/welcome/ and have a default action if I want. But then my conflict occurs between my default routing:
routes.MapPageRoute("default", "{*action}", "~/default.aspx");
I also want to access some action on my default.aspx - but it seems I cant when Im doing it like this?
It will pick the file line and go with that, so I cant do mysite.com/logout/ which is a function on my default.aspx page, it will ofcouse look for a file in this case.. Is there any other way to do what I want? So I can use both routes?
Hope you can help me out
Kind regards
It will always take the first route and go with it. In your case, it will look for logout.aspx which doesn't exist. The only option is to use the URL mysite.com/default/logout.
We can consider this as a limitation of URL Routing in WebForms.
You can check my blog series for URL Routing in Web forms at following URL.
http://karmic-development.blogspot.in/2013/10/url-routing-in-aspnet-web-forms-part-1.html
http://karmic-development.blogspot.in/2013/10/url-routing-in-aspnet-web-forms-part-2.html
There are more articles in this series.

Redirecting url to index.aspx page using standard asp.net3.5 and web.config

I have a subdomain that is http://trade.businessbazaar.in . I am dynamically creating urls from database something in this manner http://trade.businessbazaar.in/mycompany. To display details, I have an index.aspx file there,thinking that on every request the index.aspx page will load and display data accodingly. Also, There is a masterpage on the index.aspx page from where i am capturing the text mycompany and query it in database to fetch result. But nothing seems to work.
A genuine link is http://trade.businessbazaar.in/Symparlife. But its unable to load index.aspx. I need a clean approach without any third party dll or rewriters. Directly to push some lines in config and start working. That is url will be the same but index page will get loaded...
In short, i want to say
I need the StackOverflow type clean url mechanism to fetch pages
Thanks in Advance
You can handle the Begin_Request event in Global.asax and add custom code to redirect to index.aspx and convert the parts of the URL into query string arguments. You should use Server.Transfer to keep the URL in the browser.
I'd recommend upgrading to 4.0 and using the Routing enine though. You should check if the standard routing is available as a download for ASP.NET 3.5. I am sure your code will get messy very soon. Been there, done that.
As #Mike Miller mentions in the comments the Routing engine ships with ASP.NET 3.5. You can check the documentation here - http://msdn.microsoft.com/en-us/library/system.web.routing(v=vs.90).aspx
Here is a tutorial on how to use it with Web Forms - http://weblogs.asp.net/scottgu/archive/2009/10/13/url-routing-with-asp-net-4-web-forms-vs-2010-and-net-4-0-series.aspx
For your case the code would be something like:
routes.MapPageRoute("company-index", "/{company}", "~/index.aspx")
And in index.aspx you can access the route value for company like this:
string company = (string)Page.RouteData.Values["company"];
Keep in mind that you'd better add something in the URL before your actual argument (the company name). If you don't you will have problems later on when because you may want to add a URL like "/Login" but then you will have to validate that users can't create a company named "Login". Not how Stack Overflow has "/questions/" before the actual question info in the URL.

URL shortener using c#

I would like to shorten a url (e.g. http://www.abc.com/products/bag.aspx) to something like (http://short.me/bag). I have found that rules can be added to web.config to detect the short link to open the correct page. But I need a dynamic web.config. Is it a good idea to keep updating the web.config whenever a user creates the short url? Or is there a better way to do it?
I have tried YOURLS, RewriteRule, etc. All don't seems to work properly on my server. I am using a WIN server. I don't really want to use the bitly API as I would like to have my own domain in front of the link. Or is there a way to use the bitly API and still retaining my domain name?
Thank you.
You need to create a database mapping short URLs to long URLs.
You would then create an HTTP handler that looks up the short URL in that database and redirects to the corresponding long URL.
Then, register that handler to run for all requests.
Bit.ly lets you use custom domain names now: https://bitly.com/pro/products, check out this part of their FAQ

Hiding default.aspx from the URL

I wanted to know if there is a solution using IIS6 for an application to get rid of the default.aspx text in the url. so for example if a user hits:
www.website.com/default.aspx
the browser only shows:
www.website.com/
No matter what.
It's just for SEO.
I already use UrlRewriting.NET for some rewrites in my app but for I'm not that clever to create a rule for that.
Any help is much appreciate.
Thanks.
Jose
I think ScottGu already has the topic of rewriting in ASP.NET covered: http://weblogs.asp.net/scottgu/archive/2007/02/26/tip-trick-url-rewriting-with-asp-net.aspx.
He covers things such as:
Rewriting using UrlRewriter.net, ISAPI Rewrite
ASP.NET Tricks, posting back (hitting the friendly version of the url)
With your problem I think you need to use a combination of, never linking to 'default.aspx' ie. ONLY link to '/'. Then use Scott's Form Postback browser file to ensure postbacks always hit that same friendly version of the url.
Redirecting 'default.aspx' to '/', which then gets served by 'default.aspx' sounds like a recipe for disaster to me. Just fix your links to ensure you never end up on 'default.aspx' explicitly.
I think the simplest way to change the search results index (assuming it knows about HTTP 301) is to write a little function in your default.aspx's Page_Load that redirects the browser using a 301 Moved Permanently (or 302 Moved Temporarily).
void Page_Load(...) {
if(Request.Path.EndsWith("default.aspx", true/*case-insensitive*/, null)) {
Response.StatusCode = 301;
Response.StatusDescription = "Moved Permanently";
Response.Headers.Add("Location", "/");
HttpContext.Current.ApplicationInstance.CompleteRequest(); // end the request
}
// do normal stuff here
}
If you have something to do URL rewriting, then all you need to do its ensure that your links point to the correct URL.
If you don't fix your links, its up to the browser to decide if it wants to display the actual link it requested.
If you would really like to do a dodgy job, you can use some javascript to make the address bar of the browser display whatever you like, even if its invalid.
If default.aspx is set as the default document to serve in IIS, and all your internal site links contain URL's without the default.aspx then I think that should do the trick.
Although the user can still type in default.aspx, search engine spiders should just pick up the friendlier URL's from your link href attributes.
The way I would do it is to use Application_BeginRequest in public class Global : System.Web.HttpApplication and check the HttpContext.Current.Request.URL for default.aspx, and then use HttpContext.Current.Response.Redirect from there if you find it.
The downside is having a redirect is not always so great and this isn't going to work if you are posting data to that default.aspx page. But you can't simply trick the browser into showing a different url, though you can tell ASP.NET to serve whatever page you want for any request.

Using a custom URL rewriter, IIS6, and urls with .htm, .html, etc

I have a custom site I'm building with automatic url rewriting using a custom engine. The rewriting works fine as long as the page url doesn't end in somehting like .htm or .html. For these pages it goes directly to the iis 404 page instead of hitting my rewriting engine first.
I have the * wildcard handler in the "Home Directory" section of the IIS6 configuration of that website but these urls seem to be ignored by it (altho things like css, jpg, js, etc to get sent to the url handler in my web project). How do i set up IIS6 to force these urls to get sent to the handler, while still serving the page if it exists normally?
The handler basically does this
if (!File.Exists(Request.Path))
{
doMyRewriting();
}
I have to assume that using a block like this (just and example, the real one does some other stuff to format the Request.Path to be proper with everything) should run the "doMyRewriting()" if the requested file does not exist otherwise it will serve the page normally. Am I mistaken?
If I tell IIS specifically to send .htm and .html pages thru to the .NET handler the rewriting works but if the page is actually there it will not serve it.
Any help would be greatly appreciated.
Thanks in advance!
Don't know if you can or would want to do this, but there is the Ionics Isapi url rewriter you can use.
http://www.codeplex.com/IIRF
Basically install that then set a rule to remove the .html that way it hits your rewrite engine. I use it on IIS 6 with several of my blogs.
I think if you are having IIS send all requests to .NET and your handler, then your handler will need to detect if the page exists and serve it instead of rewriting.
UrlRewriting.NET has an option to do this - you might want to look at their code to see how they're handling this case.
In my opinion, rewriting URLs with IIS 6 is best handled with an ISAPI filter written as unmanaged native code. Otherwise, you run into the issues you've mentioned - having to map all extensions to ASP.Net and losing the ability for simple file handling. With an ISAPI filter, you can choose to not rewrite some URLs and let IIS handle them as normal.
To get started, I suggest reading the ISAPI Filter Overview on MSDN.
If your filter absolutely needs the .Net framework runtime, it is possible to write a small ISAPI filter shell that hosts the CLR and forwards the requests to some managed code. The Filter.Net Framework takes this approach and may be suitable for your needs. There is the small drawback to this approach in that you will have to use the same .Net version as any ASP.Net applications that are run in the main IIS process.

Categories

Resources