1

I wrote Azure Function in C#. This function must send request to external API with many params. It looks like this:

 using (var client = new HttpClient())
            {
                var url = new Uri ("http://externalapi/data/save");

                var response = await client.GetAsync(url + string.Format("?param1={0}&param2={1}&level={2}&dt_event={3}&DeviceId={4}&Apid={5}",humidity, temperature, level, data.dateTime, data.deviceId, data.apid));
                var content = await response.Content.ReadAsStringAsync();
                // log.LogInformation("Message displayed: {content}", content);
            }

I have question related with GetAsync line. Is it possible to write it in a more transparent way than I wrote it? I've seen many solutions, but I've done the same as mine.

Of course, this solution works, but I would like to write it in a more optimal way.

PawelC
  • 1,128
  • 3
  • 21
  • 47
  • Instead of `string.format()` I would use `$"?param1={humidity}&param2={temperature}..."` Is that what you mean? It makes it somewhat better readable – silent May 21 '19 at 13:51
  • 3
    btw, usually in an Azure Function, don`t use your HttpClient in a using() statement. Instead use a static HttpClient which can be reused in many function executions – silent May 21 '19 at 13:52
  • This has nothing to do with azure function or azure in general. It's a httpclient or Uri building question. – Erndob May 21 '19 at 13:54
  • 1
    @Erndob i change title and tags – PawelC May 21 '19 at 13:57

1 Answers1

0

If you use RestSharp (http://restsharp.org/) you can do

var client = new RestClient("http://externalapi");

var request = new RestRequest("data/save", Method.GET)
    .AddQueryParameter("param1", humidity)
    .AddQueryParameter("param2", temperature)
    .AddQueryParameter("level", level)
    .AddQueryParameter("dt_event", DataFormat.dateTime)
    .AddQueryParameter("DeviceId", data.deviceId)
    .AddQueryParameter("Apid", data.apid);

var response = await client.ExecuteAsync(request);
var content = response.Content; // raw content as string

or you can have a Dictionary<string, string> with your mapping and call .AddQueryParameter in a foreach. which ever makes the code more readable to you.

ahmelsayed
  • 7,125
  • 3
  • 28
  • 40