While working in ASP.NET projects, I often come across joining or combining URLs or URIs. We can combine or join URIs in several ways. In this article, I will show you the best method for combining URIs in ASP.NET with Razor and C#.
Combining URLs in Razor
The correct way to combine URIs in Razor is to use uribuilder. here is an example of how to combine “http://mytecbits.com” and “/tools/cryptography”.
@{ UriBuilder UriBuilder = new UriBuilder("http","mytecbits.com",80, "/tools/cryptography"); @Html.Raw(UriBuilder.ToString()); }
Combining URIs in C#
The best way to join URLs in C# code in ASP.NET is to use the System.Uri class. Here is a sample for joining URIs in C# code in controller of ASP.NET project.
public ActionResult Index() { Uri bUri = new Uri("http://mytecbits.com"); Uri finalUri = new Uri(bUri, "/tools/cryptography"); ViewBag.Uri = finalUri.ToString(); return View(); }
Reference
- About System.Uri at Microsoft Docs.
You’ve not explained why this is the best way. What’s wrong with just concatenating the pieces? Why do we need to remember these esoteric class methods, not to mention some overhead and unnecessary code.