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.

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;
}
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;
}

0 Comments

Leave a Reply

Avatar placeholder

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