I am writing a C# application that needs to callout to a webapp. I am trying to use System.Uri
to combine two URL's: A base URL and the relative path to the specific service (or many) of the webapp I need. I have a class member named webappBackendURL
that I want to define in one place, with all calls building from it (webappBackendURL
is not defined as close as my examples illustrate).
System.Uri webappBackendURL = new System.Uri("http://example.com/");
System.Uri rpcURL = new System.Uri(webappBackendURL,"rpc/import");
// Result: http://example.com/rpc/import
This works, however, if webappBackendURL
contains a query string, it is not preserved.
System.Uri webappBackendURL = new System.Uri("http://example.com/?authtoken=0x0x0");
System.Uri rpcURL = new System.Uri(webappBackendURL,"rpc/import");
// Result: http://example.com/rpc/import <-- (query string lost)
Is there a better way combine URLs? The .NET library is extensive, so I'm thinking I might have just overlooked a built-in way to handle this. Ideally, I would like to be able to combine URLs like this:
System.Uri webappBackendURL = new System.Uri("http://example.com/?authtoken=0x0x0");
System.Uri rpcURL = new System.Uri(webappBackendURL,"rpc/import?method=overwrite&runhooks=true");
// Result: http://example.com/rpc/import?authtoken=0x0x0&method=overwrite&runhooks=true
To pass in parameter values, simply append them to the query string at the end of the base URL. In the above example, the view parameter script name is viewParameter1.
Any word after the question mark (?) in a URL is considered to be a parameter which can hold values. The value for the corresponding parameter is given after the symbol "equals" (=). Multiple parameters can be passed through the URL by separating them with multiple "&".
URL parameters (known also as “query strings” or “URL query parameters”) are elements inserted in your URLs to help you filter and organize content or track information on your website.
Query parameters are passed after the URL string by appending a question mark followed by the parameter name , then equal to (“=”) sign and then the parameter value. Multiple parameters are separated by “&” symbol.
You could do something like this:
System.Uri webappBackendURL =
new System.Uri("http://example.com/?authtoken=0x0x0");
System.Uri rpcURL = new System.Uri(webappBackendURL,
"rpc/import?ethod=overwrite&runhooks=true"
+ webappBackendURL.Query.Replace("?", "&"));
Try UriTemplate
:
Uri baseUrl = new Uri("http://www.example.com");
UriTemplate template = new UriTemplate("/{path}/?authtoken=0x0x0");
Uri boundUri = template.BindByName(
baseUrl,
new NameValueCollection {{"path", "rpc/import"}});
System.UriTemplate
has moved around between different versions of .NET. You'll need to determine which assembly reference is correct for your project.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With