Breaking

Monday, November 15, 2021

ASP.NET Core - Build a query string

What is wrong with the following code?

async Task<Product> SearchProducts(string searchTerm)
{
var path= $"api/products/search?searchterm={searchTerm}"
var response = await client.GetAsync(path);
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsAsync<IList<Product>>();
}
}

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:

async Task<Product> SearchProducts(string searchTerm)
{
var path= QueryHelpers.AddQueryString("api/products/search","searchTerm",searchTerm);
var response = await client.GetAsync(path);
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsAsync<IList<Product>>();
}
}

That's better!

No comments:

Post a Comment