Home > OS >  What's the correct way to send PARAMS when using HttpClient.SendAsync()?
What's the correct way to send PARAMS when using HttpClient.SendAsync()?

Time:05-07

I have an application that is using a remote API. That API requires that I send PARAMS before it will accept the request as valid. Currently I send x-www-form-urlencoded values through the Body of the API call.

WRONG WAY: enter image description here

I want to NOT send it in the Body and instead send it as Params. I was just going to add it to the end of the URL to "fix it" and move on but, I feel like the is a better way to go about it maybe? Something that accounts for converting all the special characters to URL friendly characters (like the @ character to @).

CORRECT WAY: enter image description here

Is there a proper way of adding the params to the request or do you just toss them on to the end of the Request URL (URL Endpoint)?

CodePudding user response:

From my experience I havent seen any built-in ways to handle query parameters other than to append values to the end of the request string.

If you need to ensure that the strings passed in are URL-friendly, just pass them through HttpUtlity.UrlEncode(string)

Example:

public async Task SendToApi(string param1, string param2)
{
    string requestUrl = HttpUtility.UrlEncode(
        $"https://your.api.com/api?x={param1}&y={param2}"
    )
    await _httpClient.SendAsync(requestUrl);
}

CodePudding user response:

If you're going to do this for multiple calls that have different query string parameters, you can do something like this:

private static string GetQueryString(object obj)
{
    var objectAsJsonString = JsonSerializer.Serialize(obj);
    var objectAsDictionary = JsonSerializer.Deserialize<IDictionary<string, object>>(objectAsJsonString);

    if (objectAsDictionary == null)
        throw new Exception($"Unable to deserialize json to query string. Json: {objectAsJsonString}");

    var objectAsListOfProperties = objectAsDictionary
        .Select(x => $"{GetUrlEncodedValue(x.Key)}={GetUrlEncodedValue(x.Value.ToString())}")
        .ToList();

    return string.Join("&", objectAsListOfProperties);
}

private static string GetUrlEncodedValue(object value)
{
    if (value is DateTime dt)
        return HttpUtility.UrlEncode(dt.ToString("O"));

    return HttpUtility.UrlEncode(value.ToString());
}
  • Related