.NET相当于curl将文件上传到REST API?

sta*_*ith 5 .net c# rest curl httpwebrequest

我需要将一个ics文件上传到REST API.给出的唯一示例是curl命令.

用于使用curl上传文件的命令如下所示:

curl --user {username}:{password} --upload-file /tmp/myappointments.ics http://localhost:7070/home/john.doe/calendar?fmt=ics
Run Code Online (Sandbox Code Playgroud)

如何在C#中使用HttpWebRequest执行此操作?

另请注意,我可能只将ics作为字符串(而不是实际文件).

sta*_*ith 5

我设法找到了一个有效的解决方案.怪癖是将请求的方法设置为PUT而不是POST.以下是我使用的代码示例:

var strICS = "text file content";

byte[] data = Encoding.UTF8.GetBytes (strICS);

HttpWebRequest request = (HttpWebRequest)WebRequest.Create ("http://someurl.com");
request.PreAuthenticate = true;
request.Credentials = new NetworkCredential ("username", "password");;
request.Method = "PUT";
request.ContentType = "text/calendar";
request.ContentLength = data.Length;

using (Stream stream = request.GetRequestStream ()) {
    stream.Write (data, 0, data.Length);
}

var response = (HttpWebResponse)request.GetResponse ();
response.Close ();
Run Code Online (Sandbox Code Playgroud)