Combining URLs or URIs in ASP.NET

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 URLs in ASP.NET

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


0 thoughts on “Combining URLs or URIs in ASP.NET”

  1. 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.

    Reply

Leave your thoughts...

This site uses Akismet to reduce spam. Learn how your comment data is processed.