Webclient 等效于 CURL 命令

Webclient equivalent of CURL command

我正在尝试通过 POST 将文件上传到 c# winform 中的 REST API。

如果我运行使用curl命令成功上传文件:

curl.exe -H "Content-type: application/octet-stream" -X POST http://myapiurl --data-binary @C:\test.docx

我试过在我的 WinForm 中使用 WebClient:

using (var client = new WebClient())
            {
                client.Headers.Add("Content-Type", "application/octet-stream");

                byte[] result = client.UploadFile(url, file);
                string responseAsString = Encoding.Default.GetString(result);
                tb_result.Text += responseAsString;
            } 

但我刚得到一个 (500) 内部服务器。

使用 fiddler 进行检查,以下 headers 添加了 CURL:

POST http://myapiurl HTTP/1.1
User-Agent: curl/7.33.0
Host: 10.52.130.121:90
Accept: */*
Connection: Keep-Alive
Content-type: application/octet-stream
Content-Length: 13343
Expect: 100-continue

但是检查我的 WebClient 方法显示如下:

POST http://myapiurl HTTP/1.1
Accept: */*
Content-Type: multipart/form-data; boundary=---------------------8d220bbd95f8b18
Host: 10.52.130.121:90
Content-Length: 13536
Expect: 100-continue
Connection: Keep-Alive

如何从我的应用程序模拟上面的 CURL 命令?

How can I simulate the CURL command above from my app?

使用HttpWebRequest。它为您提供了更大的灵活性。如下:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://myapiurl");
request.Method = "POST";
request.UserAgent = "curl/7.33.0";
request.Host = "10.52.130.121:90";
request.Accept = "Accept=*/*";
request.Connection = "Keep-Alive";
request.ContentType = "application/octet-stream";
request.ContentLength = 13343;
request.Expect = "100-continue";