Search code examples
c#httpclienthttpwebrequest

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


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 %40).

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)?


Solution

  • 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);
    }