简体   繁体   English

如何在调用 C# 时在 web API 中添加参数

[英]How to add parameter in the web API while calling in C#

I have given below the sample code, I am calling web API but I am struggling to pass the parameter in the console application.我在下面给出了示例代码,我正在调用 web API 但我很难在控制台应用程序中传递参数。

C# code: C# 代码:

HttpClient client = new HttpClient();
var responseTask = client.GetAsync("<web api name>");
responseTask.Wait();

HttpRequestMessage rm = new HttpRequestMessage();
var headers = rm.Headers;

client.DefaultRequestHeaders.Add("client_id", "1234xv");
client.DefaultRequestHeaders.Add("client_secret", "7dfdfsd");

if (responseTask.IsCompleted)
{
    var result = responseTask.Result;

    if (result.IsSuccessStatusCode)
    {
        var messageTask = result.Content.ReadAsStringAsync();
        messageTask.Wait();                    
        Console.WriteLine("Message from Web API:" + messageTask.Result);                  
        Console.ReadLine();
    }
}

You were making the GET call much early, even before adding the parameters to the HTTP headers.即使在将参数添加到 HTTP 标头之前,您也很早就进行了 GET 调用。 You need to add the params and then call the GetAsync().您需要添加参数,然后调用 GetAsync()。 See the modified code below,请参阅下面的修改代码,

using (HttpClient client = new HttpClient())
{
   client.DefaultRequestHeaders.Add("client_id", "1234xv");
   client.DefaultRequestHeaders.Add("client_secret", "7dfdfsd");

   var responseTask = client.GetAsync("http://your api url");
   responseTask.Wait();
   if (responseTask.IsCompleted)
   {
      var result = responseTask.Result;
      if (result.IsSuccessStatusCode)
      {
          var messageTask = result.Content.ReadAsStringAsync();
          messageTask.Wait();
          Console.WriteLine("Message from Web API:" + messageTask.Result);
          Console.ReadLine();
      }
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM