Building URIs in .NET Core.

Creating URIs with parameters in .NET Core is more complicated than I’d initially expected. As a result I ended up creating my own methods based upon this Stack Overflow answer.

To begin with I needed a version to return relative paths I’ve also created a version to return a fully qualified URI.

These use the following packages.

  • System.Collections.Specialized
  • System.Web

These are also .NET Core 2.0 and up only as some as the objects/methods aren’t available in older versions.

Fully Qualified:

	
public static Uri BuildUri(string root, NameValueCollection query)
{
	var collection = HttpUtility.ParseQueryString(string.Empty);

	foreach (var key in query.Cast<string>().Where(key => !string.IsNullOrEmpty(query[key])))
	{
		collection[key] = query[key];
	}

	UriBuilder builder = new UriBuilder(root) { Query = collection.ToString() };
	return builder.Uri;
}
	

Relative:

	
public static string BuildRelativeUri(string root, NameValueCollection query)
{
	var collection = HttpUtility.ParseQueryString(string.Empty);

	foreach (var key in query.Cast<string>().Where(key => !string.IsNullOrEmpty(query[key])))
	{
		collection[key] = query[key];
	}

	if (root.Contains("?"))
	{
		if (root.EndsWith("&"))
		{
			root = root + collection.ToString();
		}
		else
		{
			root = root + "&" + collection.ToString();
		}
	}
	else
	{
		root = root + "?" + collection.ToString();
	}

	return root;
}
	

Leave a Reply

Your email address will not be published. Required fields are marked *


Fatal error: Uncaught GuzzleHttp\Exception\ClientException: Client error: `POST https://dc.services.visualstudio.com/v2/track` resulted in a `400 Invalid instrumentation key` response: {"itemsReceived":1,"itemsAccepted":0,"errors":[{"index":0,"statusCode":400,"message":"Invalid instrumentation key"}]} in D:\home\site\wwwroot\wp-content\plugins\application-insights\vendor\guzzlehttp\guzzle\src\Exception\RequestException.php:113 Stack trace: #0 D:\home\site\wwwroot\wp-content\plugins\application-insights\vendor\guzzlehttp\guzzle\src\Middleware.php(66): GuzzleHttp\Exception\RequestException::create(Object(GuzzleHttp\Psr7\Request), Object(GuzzleHttp\Psr7\Response)) #1 D:\home\site\wwwroot\wp-content\plugins\application-insights\vendor\guzzlehttp\promises\src\Promise.php(203): GuzzleHttp\Middleware::GuzzleHttp\{closure}(Object(GuzzleHttp\Psr7\Response)) #2 D:\home\site\wwwroot\wp-content\plugins\application-insights\vendor\guzzlehttp\promises\src\Promise.php(156): GuzzleHttp\Promise\Promise::callHandler(1, Object(GuzzleHttp\P in D:\home\site\wwwroot\wp-content\plugins\application-insights\vendor\guzzlehttp\guzzle\src\Exception\RequestException.php on line 113