GotKnowHow.com

How to Get Fully Qualified Route Urls from GetRouteUrl

by


The new Routing features in ASP.NET 4.0 are pretty awesome.  However, one issue I ran into recently was trying to get the fully qualified urls from Page.GetRouteUrl as string urls to be used in emails messages.  Unfortunately, I wanted something that worked both on the localhost development server, and on the production server.  So I ended up creating a RouteUrlToFullUrl method which will get the route url and turn it into a fully qualified url, to be used as url string in emails or when you just want the full url.

The RouteUrlToFullUrl below is in class that I call Utilities.cs

    /// 
    /// Get route url and turn it into full url, to use in emails or when you need the full url
    /// 
    public static string RouteUrlToFullUrl(string route)
    {
        if(string.IsNullOrEmpty(route))
        {
            return route;
        }

        // *** Is it already an absolute Url?    
        if (route.IndexOf("://") > -1)
            return route;

        HttpContext context = HttpContext.Current;
            return String.Concat(context.Request.Url.Scheme, "://", context.Request.Url.Authority, route);
    }

 I then use the RouteUrlToFullUrl below, to get a route's fully qualified url:

string articleUrl = Utilities.RouteUrlToFullUrl(Page.GetRouteUrl("ArticleStory", new { pathname = Page.RouteData.Values["pathname"] }));

This works with both the localhost and on a production server to get the full correct domain url.  

NOTE: 'Utilities' is just the class where the RouteUrlToFullUrl function is located in, but you can surely place RouteUrlToFullUrl anywhere in your code project. 

 


0
1

1 Comment

anonymous by Karl on 10/17/2011
Just what I needed. Thanks very much.

Add your comment

by Anonymous - Already have an account? Login now!
Your Name:  

Comment:  
Enter the text you see in the image below
What do you see?
Can't read the image? View a new one.
Your comment will appear after being approved.

Ask a Question

140 characters left

Recent Articles

Follow Us...