通过Rest c#httpClient创建jira问题

我在atlassian上看了一个答案https://answers.atlassian.com/questions/79902/using-httpclient-c-to-create-a-jira-issue-via-rest-generates-bad-request-response用户通过以下代码创建了JIRA问题。 我调整了它,但通过使用ObjectContent的自构建类问题得到错误

 Http.HttpContent content = new Http.ObjectContent(data, jsonFormatter); 

编译器不会接受它。 有人知道为什么吗?

  public string CreateJiraIssue() { string data= @"{ ""fields"": { ""project"": { ""key"": ""HELP"" }, ""summary"": ""Test Ticket"", ""description"": ""Creating of an issue using project keys and issue type names using the REST API"", ""issuetype"": { ""name"": ""Ticket"" }, ""assignee"": { ""name"": ""user"" } } }"; string postUrl = "https://xxx.jira.com/rest/api/2/"; System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(); client.BaseAddress = new System.Uri(postUrl); byte[] cred = UTF8Encoding.UTF8.GetBytes("username:password"); 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")); System.Net.Http.Formatting.MediaTypeFormatter jsonFormatter = new System.Net.Http.Formatting.JsonMediaTypeFormatter(); System.Net.Http.HttpContent content = new System.Net.Http.ObjectContent(data, jsonFormatter); System.Net.Http.HttpResponseMessage response = client.PostAsync("issue", content).Result; if (response.IsSuccessStatusCode) { string result = response.Content.ReadAsStringAsync().Result; return result; } else { return response.StatusCode.ToString(); } 

并使用

 namespace IOnotification_System { public class Issue { public Fields fields { get; set; } public Issue() { fields = new Fields(); } } public class Fields { public Project project { get; set; } public string summary { get; set; } public string description { get; set; } public Assignee assignee { get; set; } public IssueType issuetype { get; set; } public Fields() { project = new Project(); issuetype = new IssueType(); } } public class Project { public string key { get; set; } } public class IssueType { public string name { get; set; } } public class Assignee { public string name { get; set; } } } 

编辑

该消息清楚地表明System.Net.Http.ObjectContent()需要一个Issue对象作为其第一个参数。 我希望在那之后还有另一条消息说没有从字符串到问题的转换。

您正在将字符串传递给需要Issue对象的方法。 formatter用于将Issue对象转换为Json字符串。

你已经有了字符串,所以尝试转换它是没有意义的。 如果您有要转换为Json字符串的Issue实例,则只需要格式化程序。 您可以使用StringContent类并使用其Headers属性添加尚未在客户端上设置的任何标头,例如:

 var content=new StringContent(data); 

原版的

什么是错误消息以及您使用的是哪种项目? System.Net.Http.Formatting命名空间是ASP.NET Web API的一部分。 您是在构建ASP.NET应用程序,控制台应用程序还是其他什么?

除非您正在构建ASP.NET站点,否则此代码将不起作用。 如果你唯一的问题是如何解析Json请求,只需使用另一个Json反序列化类。 Json.NET是一个非常受欢迎的选择。

在任何情况下都没有理由使用Json类将字符串转换为包含完全相同字符串的HttpContent对象。 您可以使用StringContent类并使用其Headers属性添加尚未在客户端上设置的任何标头。

以下是魔术:

 var content = new StringContent(data, Encoding.UTF8, "application/json");