ResolveUrl in your Business Logic

March 15, 2009

I’ve recently started moving a large amount of code on the project I’m working on from the presentation layer into a business logic layer. One of the problems I found was trying to link to other pages on the site without know where the application would be located or if it would be http or https.

I picked up a bit of code from http://www.west-wind.com/Weblog/posts/154812.aspx to handle it, but had to make some changes to make it work in a more generic fashion. My change is small and in bold.

/// <summary>

/// Returns a site relative HTTP path from a partial path starting out with a ~.

/// Same syntax that ASP.Net internally supports but this method can be used

/// outside of the Page framework.

///

/// Works like Control.ResolveUrl including support for ~ syntax

/// but returns an absolute URL.

/// </summary>

/// <param name=”originalUrl”>Any Url including those starting with ~</param>

/// <returns>relative url</returns>

public static string ResolveUrl(string originalUrl)
{

if (originalUrl == null)

return null;

// *** Absolute path – just return

if (originalUrl.IndexOf(“://”) != -1)

return originalUrl;

// *** Fix up image path for ~ root app dir directory

if (originalUrl.StartsWith(“~”))
{

string newUrl = “”;

if (HttpContext.Current != null)

newUrl = HttpContext.Current.Request.Url.Scheme + “://” + HttpContext.Current.Request.Url.Host + HttpContext.Current.Request.ApplicationPath + originalUrl.Substring(1).Replace(“//”, “/”);

else

// *** Not context: assume current directory is the base directory

throw new ArgumentException(“Invalid URL: Relative URL not allowed.”);

// *** Just to be sure fix up any double slashes

return newUrl;

}

return originalUrl;

}

  • Share/Bookmark

Related posts:

  1. Redirecting using strong types in an asp.net web application project Update, I recommend also reading the following post after you...
  2. How to Mock the HttpContext in asp.net I find mocking the http context rather difficult, you can’t...
  3. Call MethodInfo.Invoke with an out parameter Taken from http://www.galcho.com/Blog/P… Here is how to call a method...

Related posts brought to you by Yet Another Related Posts Plugin.

tags: , ,
posted in Programming by admin

Follow comments via the RSS Feed | Leave a comment | Trackback URL

Leave Your Comment

 
Powered by Wordpress and MySQL. Theme by Shlomi Noach, openark.org