Home > OS >  How to exclude empty params?
How to exclude empty params?

Time:07-21

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

CodePudding user response:

If you don't want to use the path segment or query param because the parameter a or b is empty or null use an if statement:

var res = baseUrl;

if(!string.IsNullOrWhiteSpace(a))
{
    res = res.AppendPathSegment(a);
}
if(!string.IsNullOrWhiteSpace(b))
{
   res = res.SetQueryParam(b);
}

CodePudding user response:

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.

  • Related