使用Azure DevOps REST API添加工作项评论遇415错误求助
Fixing 415 Unsupported Media Type When Adding Azure DevOps Work Item Comments via REST API
Let's break down why you're hitting that 415 error and fix it step by step:
The Root Cause
Your code has two key mismatches with the Azure DevOps REST API requirements for the 5.1-preview.3 comments endpoint:
- Wrong Content-Type: You're using
application/json-patch+json(this is meant for PATCH requests to update work item fields, not POST requests to add comments). - Incorrect Request Body Format: The endpoint expects a single comment object, not an array of comments.
Corrected Code
Here's the adjusted version of your code that should resolve the issue:
public class Comment { [JsonProperty("text")] public string Text { get; set; } } // Create a single comment object instead of wrapping it in a list var comment = new Comment() { Text = "Test Comment" }; var body = JsonConvert.SerializeObject(comment); // Use "application/json" as the content type (matches API expectations for POST) var postValue = new StringContent(body, Encoding.UTF8, "application/json"); using (HttpClient httpClient = new HttpClient()) { httpClient.DefaultRequestHeaders.Accept.Clear(); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "", _token)))); // Use async/await instead of .Result for non-blocking calls (best practice) using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, _apiUrl) { Content = postValue }) { var httpResponseMessage = await httpClient.SendAsync(httpRequestMessage); // Add this to throw an exception if the request fails (helps with debugging) httpResponseMessage.EnsureSuccessStatusCode(); } }
Key Changes Explained
- Content-Type Fix: Switched from
application/json-patch+jsontoapplication/json— this aligns with what the API expects for POST requests to create comments. - Request Body Fix: Removed the
List<Comment>wrapper and serialized just the singleCommentobject. The API doesn't accept an array here, which was contributing to the invalid request format. - Async/Await Update: Replaced
.Resultwithawait(ensure your containing method is markedasync) to avoid blocking calls, which is a standard best practice for HttpClient usage.
Additional Checks
- Double-check that your
_apiUrlfollows the correct pattern:https://dev.azure.com/{org}/{proj}/_apis/wit/workItems/{id}/comments?api-version=5.1-preview.3 - Confirm your personal access token (
_token) has the Work Items (Read & Write) permission scoped to the target project.
内容的提问来源于stack exchange,提问作者Nitin Manju
相关产品推荐
相关产品推荐

