The problem
I have a web site with some articles inside. Articles are accessed using a database writing results on a single page. When a certain article is to be accessed, I need the article-id and I only need to get to the page: http://www.mysite/Articles.aspx?a={article-id}
.
This is nice but not really friendly and not scalable. What I want to do is to redirect every url in the form: http://www.mysite/articles/{article-id}
to the page http://www.mysite/Articles.aspx?a={article-id}
.
I know that using Web.Config
I can use the urlMappings
settings, but do not know how to insert a regex there.
Some notes
Please consider that I would like to have a simple translation tool. I do not want to edit my existing pages. This solution should be as transparent as possible to my application components.
What is the best practice to get to the solution?
I think you should use:
- ASP.NET Routing
Eg.:
protected void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapPageRoute("Articles",
"articles/{article-id}/",
"~/Articles.aspx");
}
& on "Articles.aspx.cs" you can get the "article-id" using:
string article-id = Page.RouteData.Values["article-id"] as string;
- Using the URL Rewrite Module
- urlrewriter.net
Details: Would you be fine with
http://www.mysite/Articles?a={article-id}
If so Microsoft Friendly Urls would be good for you. You would not need to change any of your existing functionality, you would just need to add the package and then add one line to Global.asax file. Also all your other Url's would be clean (i.e. http://www.mysite/Articles, http://www.mysite/About). It works for Web Site/Forms but does not work for Web Pages (i.e. Web Matrix)
Solution:
- In solution Explorer, right click on your Website and select "Manage Nuget Packages.."
- Press the drop down that says "Stable Only" and choose "Include Prerelease" (it is in Pre-Release)
- In the search box enter "Microsoft.AspNet.FriendlyUrls"
- Select "Install"
- Add a Global Application Class "Global.asax"
In the Application_Start method add the following line
RouteConfig.RegisterRoutes(System.Web.Routing.RouteTable.Routes);
You will now have FriendlyURL's
Note: If you are using a web site you will need to delete the following files for it to work (It will work fine with Web forms. Once it becomes a stable release I am sure you wont need to delete these files)
- Site.Mobile.Master
- Site.Mobile.Master.designer.cs
- ViewSwitcher.ascx
- ViewSwitcher.ascx.designer.cs
Links To More Information:
Information on Microsoft's Friendly Url Package