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

Related Articles & Tools

Leave your thoughts...