Search code examples
c#flurl

How to exclude empty params?


i'm building an url using flurl. This is an example of what i am doing:

var res = baseUrl.AppendPathSegment(a).SetQueryParam(b);

I would like to make flurl skip adding "a" or "b" when they are string.empty. Is that possible?

At the moment i see that flurl is adding "a" and "b" to the url even if they are empty.

Thank you


Solution

  • Let's test a few scenarios:

    "http://example.com/".AppendPathSegment("").AppendPathSegment("")
    

    Result: http://example.com/, which (if I understand you correctly) is exactly what you want. But, AppendPathSegment will throw an exception if you pass null, so I would suggest this in your case:

    baseUrl.AppandPathSegment(a ?? "")
    

    Next up:

    "http://example.com/".AppendPathSegment("").SetQueryParam("x", null)
    

    Also leaves you with http://example.com/. But an empty string value (instead of null) will append ?x=, so you may need to replace any empty string with null in this case.

    However, it looks like you're using the less-common overload of AppendQueryParam that takes a single argument.

    "http://example.com/".SetQueryParam("")
    "http://example.com/".SetQueryParam(null)
    

    In both cases the result is http://example.com/?. The server shouldn't behave differently in this case than it would without the ?, but if you're finding that's not true in your case, then Flurl doesn't have a built-in way to deal with it. You'll need to either avoid it with an if statement or use TrimEnd('?') on the string result.