views:

388

answers:

2

So this post talked about how to actually implement url rewriting in an ASP.NET application to get "friendly urls". That works perfect and it is great for sending a user to a specific page, but does anyone know of a good solution for creating "Friendly" URLs inside your code when using one of the tools referenced?

For example listing a link inside of an asp.net control as ~/mypage.aspx?product=12 when a rewrite rule exists would be an issue as then you are linking to content in two different ways.

I'm familiar with using DotNetNuke and FriendlyUrl's where there is a "NavigateUrl" method that will get the friendly Url code from the re-writer but I'm not finding examples of how to do this with UrlRewriting.net or the other solutions out there.

Ideally I'd like to be able to get something like this.

string friendlyUrl = GetFriendlyUrl("~/MyUnfriendlyPage.aspx?myid=13");

EDIT: I am looking for a generic solution, not something that I have to implement for every page in my site, but potentially something that can match against the rules in the opposite direction.

A: 

Create a UrlBuilder class with methods for each page like so:

public class UrlBuilder
{
    public static string BuildProductUrl(int id)
    {
        if (true) // replace with logic to determine if URL rewriting is enabled
        {
            return string.Format("~/Product/{0}", id);
        }
        else
        {
            return string.Format("~/product.aspx?id={0}", id);
        }
    }
}
John Sheehan
I'm trying to find something more generic, so that I don't have to maintain two collections of rewriting rules, one inside UrlRewriting.net and one inside my code.
Mitchel Sellers
+3  A: 

See System.Web.Routing

Routing is a different from rewriting. Implementing this technique does require minor changes to your pages (namely, any code accessing querystring parameters will need to be modified), but it allows you to generate links based on the routes you define. It's used by ASP.NET MVC, but can be employed in any ASP.NET application.

Routing is part of .Net 3.5 SP1

David Thibault