.NET相当于卷曲上传文件到REST API?卷曲、上传文件、NET、REST

2023-09-04 01:59:32 作者:撩妹老手.

我需要一个ICS文件上传到一个REST API。给出的唯一的例子是一个curl命令。

I need to upload an ics file to a REST API. The only example given is a curl command.

用来上传使用curl该文件的命令是这样的:

The command used to upload the file using curl looks like this:

curl --user {username}:{password} --upload-file /tmp/myappointments.ics http://localhost:7070/home/john.doe/calendar?fmt=ics

我怎样才能做到这一点在C#中使用的HttpWebRequest?

How can I do this using a HttpWebRequest in C# ?

另外请注意,我可能只拥有集成电路为一个字符串(而不是实际的文件)。

Also note that I may only have the ics as a string (not the actual file).

推荐答案

我得到了一个有效的解决方案。的怪癖是设置请求的方法将代替POST。这里是code我用了一个例子:

I managed to get a working solution. The quirk was to set the method on the request to PUT instead of POST. Here is an example of the code I used:

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 ();