What is wrong with the following code?
Nothing you would say? What if I passed ‘Bert & Ernie’ as the searchterm parameter?
The problem is that I’m using string interpolation to build up the query. This could be OK if you have full control on the passed parameters but in this case it is input coming from a user. The example above would lead to an incorrect query string.
Writing the correct logic to handle ampersands, question marks and so on would be a challenge. Luckily ASP.NET Core offers a QueryHelpers clas with an AddQueryString function:
public
static
string
AddQueryString(
string
uri,
string
name,
string
value);
public
static
string
AddQueryString(
string
uri, IDictionary<
string
,
string
> queryString);
Let’s update our code example to use this:
That's better!