Kumar Ashwin Hubert
Ashwin's Blog

Follow

Ashwin's Blog

Follow
Flurl - The elegant way to build URLs & set query params in .Net

Flurl - The elegant way to build URLs & set query params in .Net

Kumar Ashwin Hubert's photo
Kumar Ashwin Hubert
·Feb 25, 2021·

3 min read

Play this article

A common task when calling web apis or resources from code is building a URL and adding the necessary query string and parameters.

The most common, naive and frequent code that we see to achieve this is :

var userId = 1;
var completed = true;
var someParamValue = "abc";

Uri baseAddress = new Uri("https://jsonplaceholder.typicode.com/");
Uri apiUrl = new Uri($"/todos?userId={userId}&completed={completed}" +
                $"&someParam={someParamValue}", UriKind.Relative);

And the typical issue with the above code is that you could accidentally miss the starting ? or the & and = in the query parameters and create bugs; another issue is the readability of the code. When there is a high number of query parameters in the url, the code tends to be messy and unclean.

Flurl to the rescue.

Flurl is a modern, fluent, asynchronous, testable, portable, buzzword-laden URL builder and HTTP client library for .NET

Flurl adds extension methods to strings which helps us easily add path segment, set query params, set fragment, etc. in a clean and elegant manner.

Installing Flurl

Flurl can be installed via NuGet Package manager console as:
PM> Install-Package Flurl

Or via the NuGet Package manager UI:

Installing flurl.png

Once installed, import the Flurl namespace and convert the messy URLs to more readable ones.

The initial code can now be modified and constructed with flurl as :

using Flurl;

string url = "https://jsonplaceholder.typicode.com/"
    .AppendPathSegment("todos")
    .SetQueryParam("userId", userId)
    .SetQueryParam("completed", completed)
    .SetQueryParam("someParam", someParamValue);

Apart from SetQueryParam there's also SetQueryParams extension that accepts object, any collection of key-value pairs, Tuples, or a Dictionary object.

Flurl extension methods are available on String as well on System.Uri. In either case, it's easy to convert back and forth using the ToString() and ToUri() methods.

using Flurl;

Uri url = "https://jsonplaceholder.typicode.com/"
    .AppendPathSegment("todos")
    .SetQueryParams(new
    {
        userId = userId,
        completed = completed,
        someParam = someParamValue
    })
    .ToUri();

Flurl provides lots of other utilities and extension methods too. Do check out flurl documentation for more details.

Did you find this article valuable?

Support Kumar Ashwin Hubert by becoming a sponsor. Any amount is appreciated!

Learn more about Hashnode Sponsors
 
Share this