C# - 无法使这个看似简单的 Web 请求正常工作

C# - Can't get this seemingly simple web request working

我有以下 powershell Web-Request 可以正常工作,可以向 PTZ 摄像机发送命令:

Invoke-WebRequest -UseBasicParsing -Uri "http://192.168.111.75/ajaxcom" `
-Method "POST" `
 -Headers @{
 "Accept"="application/json, text/javascript, */*; q=0.01"
   "Accept-Encoding"="gzip, deflate"
   "Accept-Language"="en-US,en;q=0.9"
   "DNT"="1"
   "Origin"="http://192.168.111.75"
   "X-Requested-With"="XMLHttpRequest"
 } `
 -ContentType "application/x-www-form-urlencoded; charset=UTF-8" `
 -Body "szCmd=encodedStringHere"

我试图在 C# 中重新创建它,但我似乎无法让它工作..

我已经尝试了一大堆东西,但这是我的代码现在的样子:

 public async static void Execute()
{
    using HttpClient client = new HttpClient();
    
   // client.DefaultRequestHeaders.Accept.Add(
   //     new MediaTypeWithQualityHeaderValue("application/json, text/javascript, */*; q=0.01"));
   // client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip, deflate"));
   // client.DefaultRequestHeaders.AcceptLanguage.Add(new StringWithQualityHeaderValue("en-US,en;q=0.9"));
    client.DefaultRequestHeaders.Add("DNT", "1");
    client.DefaultRequestHeaders.Add("Origin", "http://192.168.111.75");
    client.DefaultRequestHeaders.Add("X-Requested-With", "XMLHttpRequest");
    string stringData = "{\"SysCtrl\":{\"PtzCtrl\":{\"nChanel\":0,\"szPtzCmd\":\"right_start\",\"byValue\":50}}}";
    var data = Encoding.Default.GetBytes(stringData);
    KeyValuePair<string, string> kvp = new KeyValuePair<string, string>("Body", data.ToString());
    var content = new FormUrlEncodedContent(new[] { kvp });
    var response = await client.PostAsync("http://192.168.111.75/ajaxcom", content);
    var responseString = await response.Content.ReadAsStringAsync();
}

我不知道为什么我遇到了这么多麻烦,感谢您的帮助

嗯,这部分是一道题:

 string stringData = "{\"SysCtrl\":{\"PtzCtrl\":{\"nChanel\":0,\"szPtzCmd\":\"right_start\",\"byValue\":50}}}";
    var data = Encoding.Default.GetBytes(stringData);
    KeyValuePair<string, string> kvp = new KeyValuePair<string, string>("Body", data.ToString());
  

您正在 Byte[] 上调用 ToString ( data.ToString() )。不确定你在期待什么,但输出实际上是字符串“System.Byte[]”你是想将它转换为 base 64 还是什么?