2014-07-23 161 views
1

我正在使用jira api添加附件到问题JIRA REST API如何使用c添加附件#

根据文档,我设置了一些东西。

1)用请求提交X-Atlassian-Token:nocheck的标题。

2)包含附件的multipart/form-data参数的名称必须是“file”。

3)资源需要多部分发布。

& 当我运行我的代码我得到内部服务器错误。

我的代码如下

string postUrl = "http://localhost:8080/rest/api/latest/issue/TES-99/attachments"; 
     System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(); 

     client.DefaultRequestHeaders.Add("X-Atlassian-Token", "nocheck"); 
     client.BaseAddress = new System.Uri(postUrl); 
     byte[] cred = UTF8Encoding.UTF8.GetBytes(credentials); 
     client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(cred)); 
     var content = new MultipartFormDataContent(); 
     var values = new[] 
      { 
       new KeyValuePair<string, string>("file", "e:\\z.txt")    
      }; 

     foreach (var keyValuePair in values) 
     { 
      content.Add(new StringContent(keyValuePair.Value), keyValuePair.Key); 
     } 

     var result = client.PostAsync(postUrl, content).Result; 

请建议我在哪里犯错

回答

1

我解决了这一点。现在我可以使用JIRA API与C#添加附件。

我对这段代码犯了错误。

 var values = new[] 
     { 
      new KeyValuePair<string, string>("file", "e:\\z.txt")    
     }; 

    foreach (var keyValuePair in values) 
    { 
     content.Add(new StringContent(keyValuePair.Value), keyValuePair.Key); 
    } 

这是我的代码。

 string postUrl = "http://localhost:8080/rest/api/latest/issue/" + projKey + "/attachments"; 

     System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(); 

     client.DefaultRequestHeaders.Add("X-Atlassian-Token", "nocheck"); 

     client.BaseAddress = new System.Uri(postUrl); 

     byte[] cred = UTF8Encoding.UTF8.GetBytes(credentials); 

     client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(cred)); 

     client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));              

     MultipartFormDataContent content = new MultipartFormDataContent(); 

     **//The code which solved the problem** 

     HttpContent fileContent = new ByteArrayContent(File.ReadAllBytes(filePath)); 

     fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse(mimeType); 

     content.Add(fileContent, "file",fileName); 

     var result = client.PostAsync(postUrl, content).Result; 
+0

这工作。但是你的代码缺少'mimeType'变量声明。它应该是字符串mimeType = System.Web.MimeMapping.GetMimeMapping(fileName); – muruge

+0

对不起,我很久以前就做过:)。当我这样做的时候不能联系到。感谢您指出我错过了这里。但我相信我已经使用这个即时通讯我的原始代码 – iGod