Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I parse and rebuild a URL in ASP.Net?

Tags:

c#

url

parameters

I'm devloping a C#/ASP.Net app and I'm trying to find a means of breaking down a URL into its component parts, then swapping out, or deleting these parts and creating a new URL.

For example if I have the following URL:

  • https://www.site.com/page.aspx?parm1=value1&parm2=value2

I'd like to split the URL down into:

  • Protocol (http, https, ftp, etc)
  • Domain (www.site.com)
  • Page (page.aspx)
  • URL parameters (parm1 = value1, parm2 = value2)

Once the URL is split down I'd like to manipulate each of the parts, for example:

  • add or remove parameters
  • change the value of parameters
  • change the page from page.aspx to page2.aspx

Then once I'm done create a new URL ready for use with the above changes.

I've checked out the MSDN documentation etc and can't find a utility class in .Net to take care of this. Any ideas?

Cheers, Steve

like image 676
Steve Parsons Avatar asked Aug 31 '25 20:08

Steve Parsons


1 Answers

The framework comes with the UriBuilder class for this purpose.

It has get/set properties for the things you need:

  • Protocol: Scheme property
  • Domain: Host property
  • Page: Path property (will give you whole path, you might need to do some processing here).
  • Parameters: Query property (exposed as a string, you might need to do some processing on the string your self).

When you are done manipulating the UriBuilder, use the Uri property to get the result as a Uri object, or just ToString() if you just need the URL as a string.

like image 71
driis Avatar answered Sep 03 '25 08:09

driis