使用C#调用POST请求调用。将PowerShell代码转换为CSharp代码

时间:2019-06-19 18:36:21

标签: c# visual-studio powershell

如何将这一行PowerShell代码转换为C#代码

Invoke-RestMethod-方法发布-Uri'https://s16events.azure-automation.net/webhooks?token=sdnfgknsdkfglkshnklsdfhgoihohsndfgndfgknkkdfg'

我正在使用Visual Studio执行此操作

请让我知道

谢谢

1 个答案:

答案 0 :(得分:0)

使用HttpClient

// HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
static readonly HttpClient client = new HttpClient();

static async Task Main()
{
  // Call asynchronous network methods in a try/catch block to handle exceptions
  try   
  {
     HttpResponseMessage response = await client.PostAsync("https://s16events.azure-automation.net/webhooks?token=sdnfgknsdkfglkshnklsdfhgoihohsndfgndfgknkkdfg", new StringContent(requestBody));

     response.EnsureSuccessStatusCode();

     string responseBody = await response.Content.ReadAsStringAsync();

     Console.WriteLine(responseBody);
  }  
  catch(HttpRequestException e)
  {
     Console.WriteLine("\nException Caught!");  
     Console.WriteLine("Message :{0} ",e.Message);
  }
}

示例改编自https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netframework-4.8