I am working on a C# project which basically works on commands to perform certain operations. It uses CommandLineParser library to parse all these commands and respective argument.
As per the new business requirement, I need to parse an URL which contains verb and parameters.
Is there any built-in/easy way to parse URL in CommandLineParser library, that will avoid writing custom logic which I explained in below approach?
Here is my approach to solve this challenge:
Covert URL to command, then using CommandLine parser assign values to option properties.
e.g.
URL:
https://localhost:9000/Open?appId=123&appName=paint&uId=511a3434-37e0-4600-ab09-65728ac4d8fe
Implementation:
Custom logic to covert url to command
open -appId 123 -name paint -uid 511a3434-37e0-4600-ab09-65728ac4d8fe
Then pass it to parser.ParseArguments
Here is the class structure
[Verb("open", HelpText = "Open an application")]
public class OpenOptions
{
[Option("id", "appId", Required = false, HelpText = "Application Id")]
public int ApplicationId{ get; set; }
[Option("name", "appName", Required = false, HelpText = "Application Name")]
public string ApplicationName{ get; set; }
[Option("uId", "userId", Required = true, HelpText = "User Id")]
public Guid UserId{ get; set; }
}
There is no out-of-the-box solution. Normally HttpUtility
class (ref Get URL parameters from a string in .NET) can do the trick.
Here is the first approach:
var url = "https://localhost:9000/Open?appId=123&appName=paint&uId=511a3434-37e0-4600-ab09-65728ac4d8fe";
Uri uri = new Uri(url);
var @params = HttpUtility.ParseQueryString(uri.Query);
string? appId = @params.Get("appId");
Console.WriteLine(appId);
Will return 123, and so on with your other parameters.
The returned value will be a string
type. You can eventually use Guid.TryParse
to parse your Guid
object and int.TryParse
for an int
value.