首页 > 解决方案 > 将 JIRA API cURL 转换为 c# http 请求

问题描述

我有一个 cURL,我用它连接到 Atlassian JIRA API 并使用 JQL 搜索问题,按项目名称和状态过滤问题。

这是 cURL 命令,效果很好:

curl -u JIRAUSER:JIRATOKEN -X POST --data '{ "jql": "project = \"QA\" AND status=\"To Do\" " }' -H "Content-Type: application/json" https://jiraserver.atlassian.net/rest/api/2/search

我正在尝试使用 httpclient POST 方法在 c# 上重新构建它。代码如下:

static async System.Threading.Tasks.Task Main(string[] args)
        {
            using (var httpClient = new HttpClient())
            {
                using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://jiraserver.atlassian.net/rest/api/2/search"))
                {
                    var base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes("JIRAUSER:JIRA TOKEN"));
                    request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}");

                    request.Content = new StringContent("{ \"jql\": \"project = \"QA\" AND status = \"To Do\" }");
                    request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

                    var response = await httpClient.SendAsync(request);

                    Console.WriteLine(response);


                }
            }

        }

响应返回以下错误:

StatusCode:400,ReasonPhrase:'',版本:1.1,内容:System.Net.Http.HttpConnectionResponseContent

在 System.Diagnostics.Debug.Write 我收到以下错误:

错误 CS0428:无法将方法组“写入”转换为非委托类型“对象”。您是否打算调用该方法?

请给我一些提示,否则我要上吊了...

标签: c#.netrestapijira

解决方案


我建议使用 JIRA SDK 与您的 JIRA 实例交互 -> https://bitbucket.org/farmas/atlassian.net-sdk/src/master/

基本上,一组步骤是

1) initiate jira client:

    var jiraClient = Jira.CreateRestClient(<jiraURL>, <jiraUserName>, <jiraUserPwd>);

2) connect to jira, and pull based on search criteria:

     var jql =  "project = QA + " AND status in (To Do)";
    IEnumerable<Atlassian.Jira.Issue> jiraIssues = AsyncTasker.GetIssuesFromJQL(jiraClient, jql, 999);

3) then, you can enumerate in the pulled issues

    ...
    foreach(var issue in jiraIssues)
    {   
        /*      
        ... for example, some of the available attributes are:

                    issue.Key.Value
                    issue.Summary
                    issue.Description
                    issue.Updated
                    String.Format("{0}/browse/{1}", jiraURL.TrimEnd('/') , issue.Key.Value)
        ...
        */
    }                    
  • 在旁注中,建议不要使用 using(... = new HttpClient()){....}

推荐阅读