带有参数的Http GET

时间:2019-05-21 13:14:20

标签: c# dotnet-httpclient

我用C#编写了Azure函数。此函数必须将请求发送到具有许多参数的外部API。看起来像这样:

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

我有与GetAsync行相关的问题。是否可以以比我编写的方式更透明的方式编写它?我见过许多解决方案,但我做的和我的一样。

当然,此解决方案有效,但是我想以更优化的方式编写它。

1 个答案:

答案 0 :(得分:0)

如果您使用<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <h2>Tabs</h2> <p>Click on the buttons inside the tabbed menu:</p> <div class="tab"> <button class="tablinks" onclick="openCity(event, 'London')">London</button> <button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button> <button class="tablinks" onclick="openCity(event, 'Tokyo')">Tokyo</button> </div> <div id="London" class="tabcontent"> <h3>London</h3> <p>London is the capital city of England.</p> </div> <div id="Paris" class="tabcontent"> <h3>Paris</h3> <p>Paris is the capital of France.</p> </div> <div id="Tokyo" class="tabcontent"> <h3>Tokyo</h3> <p>Tokyo is the capital of Japan.</p> </div> </body> </html> http://restsharp.org/),则可以

RestSharp

或者您可以在映射中使用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 并在foreach中调用Dictionary<string, string>。从而使代码更易读。

相关问题