JIRA REST API 如何使用 C# 添加附件

标签 jira asp.net-web-api jira-rest-api jira-rest-java-api

我正在使用 jira api 为问题添加附件

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

  1. 提交 X-Atlassian-Token header :不检查请求。

  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;

请指出我哪里出错了

最佳答案

我也解决了这个问题。现在我可以通过 C# 使用 JIRA API 添加附件。

我在这段代码上犯了错误。

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;

关于JIRA REST API 如何使用 C# 添加附件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24914723/

相关文章:

c# - Web API 只允许单个异步任务

python - 可以使用 jira-python 读出搜索过滤器

spring - 在自定义 Atlassian JIRA 插件中注入(inject) SoyTemplateRenderer

.net - Azure WebJobs 有很多 QueueTrigger 不好的做法吗?

node.js - JQL查询错误: The character \'%\' is a reserved JQL character

jira - 如何获取分支/拉取请求的 JIRA 问题?

jira-rest-api - 如何使用 rest api 向 jira 问题添加评论

gradle - 将 Gradle 与 Jira 集成

linux - Linux 上的 jira 主路径错误

asp.net-web-api - ASP.NET Web API - 模型绑定(bind)不适用于 POST 上的 XML 数据