Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JIRA REST API how to add attachment using c#

I am using jira api to add attachment to the issue

According to documentation i have set few things.

  1. submit a header of X-Atlassian-Token: nocheck with the request.

  2. The name of the multipart/form-data parameter that contains attachments must be "file".

  3. resource expects a multipart post.

& when i run my code i get internal server error.

my code is as follows

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;

please suggest where i am making mistake

like image 830
Learner Avatar asked Nov 27 '25 09:11

Learner


1 Answers

I solved this too. now i am able to add attachment using JIRA API with C#.

i was making mistake with this piece of code.

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

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

this is my code.

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;
like image 159
Learner Avatar answered Nov 29 '25 22:11

Learner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!