我正在开发一个使用Redmine REST API的C#应用程序,它使用RestSharp Client。所有其他REST调用我工作正常,但我找不到上传附件的方法。我在网上广泛搜索并尝试了很多解决方案,但没有任何效果。 关于附件的Redmine记录:http://www.redmine.org/projects/redmine/wiki/Rest_api#Attaching-files 代码实际上看起来像:
RestClient client = new RestClient("http://myclient/redmine/");
client.Authenticator = new HttpBasicAuthenticator("myuser", "mypsw");
var request2 = new RestRequest("uploads.json", Method.POST);
request2.AddHeader("Content-Type", "application/octet-stream");
request2.RequestFormat = RestSharp.DataFormat.Json;
byte[] dataToSend = File.ReadAllBytes(AddIssue.attach.Text);
request2.AddBody(dataToSend);
IRestResponse response2 = client.Execute(request2);
resultbox.Text = response2.Content;
如果我执行它上面没有任何反应,响应为空。如果我删除第7行(AddBody),它实际上可以工作,但当然没有上传,JSON响应: { “上传”:{ “令牌”:“11。” } }
实际上,真正的问题是如何在AddBody()中将文件作为application / octet-stream发送。既然RestSharp也有一个request.AddFile()方法,我也用不同的方式尝试了它,但没有...
非常感谢任何帮助!
答案 0 :(得分:0)
正如我在评论中提到的,听起来像Redmine可能有类似Dropbox的要求。以下是适用于我的解决方案(基于问题 Upload to dropbox using Restsharp PCL ):
public static void UploadFileToDropbox(string filePath)
{
RestClient client = new RestClient("https://api-content.dropbox.com/1/");
IRestRequest request = new RestRequest("files_put/auto/{path}", Method.PUT);
FileInfo fileInfo = new FileInfo(filePath);
long fileLength = fileInfo.Length;
request.AddHeader("Authorization", "Bearer INSERT_DEVELOPER_TOKEN_HERE");
request.AddHeader("Content-Length", fileLength.ToString());
request.AddUrlSegment("path", string.Format("Public/{0}", fileInfo.Name));
byte[] data = File.ReadAllBytes(filePath);
var body = new Parameter
{
Name = "file",
Value = data,
Type = ParameterType.RequestBody,
};
request.Parameters.Add(body);
IRestResponse response = client.Execute(request);
}
我知道这不是你的确切情况,但希望它会给你一些想法。