URL


Get the absolute url from relative

Sometimes, like when you are setting the cannonical URL in header, you want it to be absolute. To transform a realtive URL to an absolute i prefer to use the following code:

public static string GetAbsolutUrl(string relativeUrl)
{
      if (string.IsNullOrEmpty(relativeUrl)){
           return relativeUrl;
      }
 
      if (HttpContext.Current == null){
           return relativeUrl;
      }

      if (relativeUrl.StartsWith("/")){
           relativeUrl = relativeUrl.Insert(0, "~");
      }

      if (!relativeUrl.StartsWith("~/")){
           relativeUrl = relativeUrl.Insert(0, "~/");
      }

      var url = HttpContext.Current.Request.Url;
      var port = url.Port != 80 ? (":" + url.Port) : String.Empty;

      return string.Format("{0}://{1}{2}{3}", url.Scheme, url.Host, port, VirtualPathUtility.ToAbsolute(relativeUrl));
}

 

Set valid characters for URL in Web.config

This changes which characters that is illegal to use in URL and thus causes an exception when used.

<httpRuntime relaxedUrlToFileSystemMapping="true" requestPathInvalidCharacters="&lt;,&gt;,*,%,:,\,?" targetFramework="4.5.1" />

 Set Relaxed mapping for URL in Web.config

This allows "foo.com/bar%20/hej" to work like "foo.com/bar/hej".

<httpRuntime relaxedUrlToFileSystemMapping="true" targetFramework="4.5.1" />

 

 

 


Published: 2016-08-25