C# - Uribuilder without parameter names - c#

I've just started using .netcore.
I need to create a url, I've come across UriBuilder however I can only see example of using that with named paramters e.g.: localhost?value=abc&another=def, however I want to construct without parameter names, so:
localhost/abc/def/
Is this possible, I was thinking maybe something like the below:
var request = new HttpRequestMessage();
request.RequestUri = new Uri(_myUrl);
request.Method = HttpMethod.Get;
var uriBuilder = new UriBuilder(request.RequestUri);
var query = HttpUtility.ParseQueryString(uriBuilder.Query);
query[0] = "abc"
Any help appreciated.

That's not how UriBuilder or URIs work. What you are trying to change/set is the path of the URI. That is done using the Path property, or using the relevant constructor of UriBuilder. Your example shows how to change/set the Query-String (key-value pairs, basically).
How you create the path is not the business of the UriBuilder class (see #Irdis comment about an option).
Basically, you can create your path manually using string manipulation of your choice, then assign it to the Path property, e.g.:
var b = new UriBuilder(...);
// Set other properties to your requirements
b.Path = "/the/path/ optional with spaces and other stuff/";
You can then use the UriBuilder.Uri property to get the full URI or use the UriBuilder.ToString() method to get the properly escaped URI. For the above example that would be something like:
http://localhost/the/path/%20optional%20with%20spaces%20and%20other%20stuff/

Related

RestRequest Parameters adding logic

I am having some issues finding information about adding some logic field in my RestRequest using V 107. I am trying to add a filter to my GET query
dl_document_indexed_date gt '2020-12-07T08:30:42.483Z'
There are a few other queries in the call which i am using Dictionary<string, string> to store them, and it works great however it only works if i am looking for something equal to, as adding it to the parameters it seems by default its equal to and i am not finding any way to add any other logic, gt/ge/lt/le etc. using the older version i would just append the url adding the logic i need, but i am not seeing a way to append the url either. Looking over their documentation i either missed it, cant find it, or its not there. Any help would be greatly appreciated! My method looks like this
public static async Task<string> GET_API(String RequestUrl, string RequestObject, Dictionary<string, string> parameters)
{
var request = new RestRequest(RequestObject);
var options = new RestClientOptions(RequestUrl)
{
ThrowOnAnyError = true,
Timeout = -1
};
var client = new RestClient(options);
client.Authenticator = new OAuth2AuthorizationRequestHeaderAuthenticator("Bearer " + TokenManager.GetAccessTokenString("TRN"));
foreach (var parameter in parameters)
{
request.AddQueryParameter(parameter.Key, parameter.Value);
}
var response = await client.GetAsync(request);
return response.Content.ToString();
}
I send the BaseURL , the RequestObject would be table i am calling in the base URL, and my dictionary item contains the Field name, and the field values that i am dynamically generating on another method that would append the string. and example would be
parameters.Add("dl_document_name", "TableA");
which would append the URL with dl_document_name eq 'TableA'
it would call the API after i add the OAuth Token i create and return the data i need and send it back. or another option i guess could be appending the string with the logic i need to return the data
You should use OData, it's easy to implement and it has different kind of filters, you also can set which filters are usable and which aren't.
https://www.odata.org/
I figured out a work around, if i only have one i can add it to the first parameter and adding the filter as the first key, which will work unless i have multiple conditions that are not eq
parameters.Add("filter","dl_document_indexed_date gt '2020-12-07T08:30:42.483Z'");

How to add a path parameter in a GET call using Restsharp?

I have the following url http://example-api.com/userid/1234
How can I added the 1234 path parameter to my URL.
the RestRequest class has AddParameter and ParameterType but I do not see any option for path parameter
RestRequest.AddParameter(value, ParameterType.);
Use AddUrlSegment()
https://restsharp.dev/usage.html#url-segment
var myParamValue = "1234"
var request = new RestRequest("http://example-api.com/userid/{myParam}")
.AddUrlSegment("myParam", myParamValue);

Extracting the Portion of the URL in C#

I have a URL like this:
http://www.example.com/Catalog/Category/Detail
http://www.example.com/Catalog/Products/12
Now, I want to extract the /Catalog/Category/Detail and /Catalog/Products/12 part so I can append with some other base url. How can I do that easily?
Use Uri class, and use Uri.LocalPath property like:
Uri uri = new Uri("http://www.example.com/Catalog/Category/Detail");
Console.WriteLine(uri.LocalPath); // /Catalog/Category/Detail
var segments = new Uri("http://www.example.com/Catalog/Category/Detail").Segments;
This will return
/
Catalog/
Category/
Detail

Get Partial Url from Uri

Uri url = new Uri("http://www.website.com/content/a/?filter=porn");
Is there any way only get a string with "/content/a/" from the Uri?
I mean no domain or query string parameters without having to work with strings?
Not sure why #AlexK deleted his answer, but url.AbsolutePath will give you that info.
Uri url = new Uri("http://www.website.com/content/a/?filter=porn");
Console.WriteLine(url.AbsolutePath);
// outputs /content/a
https://dotnetfiddle.net/3koJ7v

How to reliably build a URL in C# using the parts?

I keep feeling like I'm reinventing the wheel, so I thought I'd ask the crowd here. Imagine I have a code snippet like this:
string protocol = "http"; // Pretend this value is retrieved from a config file
string host = "www.google.com"; // Pretend this value is retrieved from a config file
string path = "plans/worlddomination.html"; // Pretend this value is retrieved from a config file
I want to build the url "http://www.google.com/plans/worlddomination.html". I keep doing this by writing cheesy code like this:
protocol = protocol.EndsWith("://") ? protocol : protocol + "://";
path = path.StartsWith("/") ? path : "/" + path;
string fullUrl = string.Format("{0}{1}{2}", protocol, host, path);
What I really want is some sort of API like:
UrlBuilder builder = new UrlBuilder();
builder.Protocol = protocol;
builder.Host = host;
builder.Path = path;
builder.QueryString = null;
string fullUrl = builder.ToString();
I gotta believe this exists in the .NET framework somewhere, but nowhere I've come across.
What's the best way to build foolproof (i.e. never malformed) urls?
Check out the UriBuilder class
UriBuilder is great for dealing with the bits at the front of the URL (like protocol), but offers nothing on the querystring side. Flurl [disclosure: I'm the author] attempts to fill that gap with some fluent goodness:
using Flurl;
var url = "http://www.some-api.com"
.AppendPathSegment("endpoint")
.SetQueryParams(new {
api_key = ConfigurationManager.AppSettings["SomeApiKey"],
max_results = 20,
q = "Don't worry, I'll get encoded!"
});
There's a new companion library that extends the fluent chain with HTTP client calls and includes some nifty testing features. The full package is available on NuGet:
PM> Install-Package Flurl.Http
or just the stand-alone URL builder:
PM> Install-Package Flurl

Categories

Resources