March 31, 2014

Different ways to combine urls

In asp.net, there are different way to combine urls with the easiest way to simply add multiple strings and the better way to use classes and methods already from asp.net. In this post, I will show different way to add multiple url parts to form a valid url.

In asp.net there are few classes with urls can be constructed like the Uri class. However, I actually prefer the use of UriBuilder class as it provides more options to specify the parameters like host, query string, anchor links, port number and so on. This is much easier class to work with than to build urls with other classes. So, below is the source code for two ways to build urls - one with concatenating strings and another with UriBuilder class.

String vs UriBuilder
  1. using System;
  2. using System.Text;
  3.  
  4. namespace WebApplication1
  5. {
  6.     public partial class UrlParts : System.Web.UI.Page
  7.     {
  8.         private bool isSecure = false;
  9.         private string host = "www.asp.net";
  10.         private int? port = 8080;
  11.         private string path = "mvc";
  12.         private string query = "s=entity|framework";
  13.         private string hash = "ef";
  14.  
  15.         //http: //www.asp.net/mvc?s=entity|framework#ef
  16.  
  17.         protected void Page_Load(object sender, EventArgs e)
  18.         {
  19.             Response.Write("from string: " + UrlsByStrings());
  20.             Response.Write("<br>from url builder: " + UrlsByUriClass());
  21.         }
  22.  
  23.         private string UrlsByStrings()
  24.         {
  25.             StringBuilder sb = new StringBuilder();
  26.  
  27.             if (isSecure)
  28.                 sb.Append("https://");
  29.             else
  30.                 sb.Append("http://");
  31.  
  32.             sb.Append(host);
  33.  
  34.             if (port.HasValue)
  35.                 sb.Append(":" + port.Value.ToString());
  36.  
  37.  
  38.             if (path != null)
  39.                 sb.Append("/" + path);
  40.  
  41.  
  42.             if (query != null)
  43.                 sb.Append("?" + query);
  44.  
  45.             if (hash != null)
  46.                 sb.Append("#" + hash);
  47.  
  48.             return sb.ToString();
  49.         }
  50.  
  51.  
  52.         private string UrlsByUriClass()
  53.         {
  54.             UriBuilder ub = new UriBuilder();
  55.             ub.Scheme = isSecure ? "https" : "http";
  56.             ub.Host = host;
  57.  
  58.             ub.Port = port.HasValue ? port.Value : -1;
  59.             ub.Path = path == null ? string.Empty : path;
  60.             ub.Query = query == null ? string.Empty : query;
  61.             ub.Fragment = hash == null ? string.Empty : hash;
  62.  
  63.             return ub.ToString();
  64.         }
  65.     }
  66. }

0 comments:

Reference: Shahed Kazi at AspNetify.com