Forums

Articles
Create
cancel
Showing results for 
Search instead for 
Did you mean: 

I'm trying to add An attachment to an Issue with Rest Api using C# but it returns

helpdesk
I'm New Here
I'm New Here
Those new to the Atlassian Community have posted less than three times. Give them a warm welcome!
July 18, 2023

Code: 

public static void SendFileToServer(string issueKey)
{
FileInfo fi = new FileInfo(@"H:\74715-Screen_Custodian Documents Tracking.xlsx");
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
byte[] fileContents = File.ReadAllBytes(fi.FullName);

//https://your-domain.atlassian.net/rest/api/2/issue/XYZ-315/attachments

string urlPath = "https://instance.atlassian.net/rest/api/2/issue/" + issueKey + "/attachments";
//Uri webService = new Uri(string.Format("{0}/{1}/attachments", urlPath, IssueKey));

HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, urlPath);
requestMessage.Headers.ExpectContinue = false;

MultipartFormDataContent multiPartContent = new MultipartFormDataContent("----MyGreatBoundary");
ByteArrayContent byteArrayContent = new ByteArrayContent(fileContents);
byteArrayContent.Headers.Add("Content-Type", "image/png");
byteArrayContent.Headers.Add("X-Atlassian-Token", "no-check");
multiPartContent.Add(byteArrayContent, "file", fi.Name);
requestMessage.Content = multiPartContent;

HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("email@mail.com" + ":" + "token_key")));
httpClient.DefaultRequestHeaders.Add("X-Atlassian-Token", "no-check");
try
{
Task<HttpResponseMessage> httpRequest = httpClient.SendAsync(requestMessage, HttpCompletionOption.ResponseContentRead, CancellationToken.None);
HttpResponseMessage httpResponse = httpRequest.Result;
HttpStatusCode statusCode = httpResponse.StatusCode;
HttpContent responseContent = httpResponse.Content;

if (responseContent != null)
{
Task<String> stringContentsTask = responseContent.ReadAsStringAsync();
String stringContents = stringContentsTask.Result;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}


Response: 

StatusCode: 404, ReasonPhrase: 'Not Found', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Timing-Allow-Origin: *
X-Arequestid: 4fd8a5843528593fd5f6f4675ebc0fe9
X-Seraph-Loginreason: AUTHENTICATED_FAILED
X-Content-Type-Options: nosniff
X-Xss-Protection: 1; mode=block
Atl-Traceid: 991dd907e1623a5c
Report-To: {"endpoints": [{"url": "https://dz8aopenkvv6s.cloudfront.net"}], "group": "endpoint-1", "include_subdomains": true, "max_age": 600}
Nel: {"failure_fraction": 0.001, "include_subdomains": true, "max_age": 600, "report_to": "endpoint-1"}
Strict-Transport-Security: max-age=63072000; includeSubDomains; preload
Transfer-Encoding: chunked
Cache-Control: no-store, no-transform, no-cache
Date: Tue, 18 Jul 2023 18:58:51 GMT
Set-Cookie: atlassian.xsrf.token=B659-IW08-H939-Y50O_58c27279e8f737f89f2c485a7701855499fe5be8_lout; path=/; SameSite=None; Secure
Server: AtlassianEdge
Content-Type: application/json; charset=UTF-8
}}

1 answer

0 votes
Hyrum Steffensen {Appfire}
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
July 18, 2023

Hello helpdesk,

I believe you need to add an attachment id to use the /attachments endpoint. For example:

string urlPath = "https://instance.atlassian.net/rest/api/2/issue/" + issueKey + "/attachments/10000";

See the Atlassian documentation on REST API for using the /attachments endpoint.

If you are interested in how I got this result, see my troubleshooting steps below.

Trying Out the /issue Endpoint

I see that the error message posted is "401 - Not Found". This usually means that the URL is malformed. I tried out the URL in a browser and get a similar error message. Here is the URL I used:

<BASE_URL>/rest/api/2/issue/DEMO-1/attachments

I then tried out the URL without "attachments" at the end and see data.

<BASE_URL>/rest/api/2/issue/DEMO-1

When I search for "attachment" in the JSON returned, I see something like the following (I have removed some of the data for readability).

"attachment": [ { "self": "<BASE_URL>/rest/api/2/attachment/10000", "id": "10000", "filename": "attachment name 1" }, { "self": "<BASE_URL>/rest/api/2/attachment/10002", "id": "10002", "filename": "attachment name 2" } ] 

In the results, the "self" value from the JSON seems like a good thing to try, so I tried the following in the web browser and it worked.

<BASE_URL>/rest/api/2/attachment/10000

Suggested Troubleshooting Steps:

  • Try out any Jira REST API in the web browser before trying it out in code.
  • Try the same REST API using GET (this tends to be less complicated for troubleshooting).
  • Check authentication values in the code.
  • When possible, post REST code as curl because more Community users can read and understand curl.
  • Consider troubleshooting REST endpoints using Postman. Postman has a nice code export feature you can use to export code as C#, curl or other languages. You can also import curl code.

Please let us know how it goes!

Hyrum

Suggest an answer

Log in or Sign up to answer
DEPLOYMENT TYPE
CLOUD
PRODUCT PLAN
STANDARD
PERMISSIONS LEVEL
Product Admin
TAGS
AUG Leaders

Atlassian Community Events