C#异步curl请求-如何访问响应?

时间:2019-07-03 07:55:48

标签: c# .net asynchronous jira dotnet-httpclient

我正在尝试将Jira API的curl请求示例转换为C#请求。

这是JIRA提供的原始Curl Request示例:

curl \
   -D- \
   -u charlie:charlie \
   -X GET \
   -H "Content-Type: application/json" \
   http://localhost:8080/rest/api/2/search?jql=assignee=charlie

我已将以下代码翻译为JIRA:

但是响应行不起作用-因为我已经拼凑了一些示例,但有些卡住了!

var myTask = curlRequestAsync(); // call your method which will return control once it hits await

string result = myTask.Result();
// .Result isn't defined - but I'm not sure how to access the response from my request!

任何帮助将不胜感激,因为我真的被困住了!

完整示例:

public partial class WebForm2 : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {

        var myTask = curlRequestAsync(); // call your method which will return control once it hits await

        string result = myTask.Result();
        // wait for the task to complete to continue

    }

    protected async System.Threading.Tasks.Task curlRequestAsync()
    {
        try
        {
            using (var httpClient = new HttpClient())
            {
                using (var request = new HttpRequestMessage(new HttpMethod("GET"), "http://myurl.co.uk/rest/api/2/search?jql=assignee=bob"))
                {
                    var base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes("username:password"));
                    request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}");

                    var result = await httpClient.SendAsync(request);

                    return result;
                }
            }
        }
        catch (Exception ex)
        {
            error.InnerText = ex.Message;
        }
    }
}

2 个答案:

答案 0 :(得分:4)

您应该返回Task<System.Net.Http.HttpResponseMessage>

protected async System.Threading.Tasks.Task<HttpResponseMessage> curlRequestAsync()
{
    try
    {
        using (var httpClient = new HttpClient())
        {
            using (var request = new HttpRequestMessage(new HttpMethod("GET"), "http://myurl.co.uk/rest/api/2/search?jql=assignee=bob"))
            {
                var base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes("username:password"));
                request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}");

                var result = await httpClient.SendAsync(request);

                return result;
            }
        }
    }
    catch (Exception ex)
    {
         error.InnerText = ex.Message;
    }
}

之后,您可以访问任务的响应:

var myTask = curlRequestAsync();

var result = myTask.Result.Content.ReadAsStringAsync().Result;

答案 1 :(得分:2)

由于使用async关键字,在方法范围内的方法签名(如“由编译器看到”)将被转换:

protected async Task Foo()

将成为

protected void Foo(); 

要使用async关键字返回值,则应使用以下签名:

protected async Task<T> Foo()

结果

protected T Foo()

对于呼叫者,签名保持不变。

Task上,Result未定义,因为它的性质不具有任务返回的值。另一方面,Task<T> Result

因此,为了获得“结果”,({{1}上没有定义ResultTask上是),您应该使用Wait,其中{定义了{1}}。

您应将签名更改为:

Task<T>

如果您处于异步范围内,则现在可以接听Resultprotected async System.Threading.Tasks.Task<WhatEverTypeYouAreReturning> curlRequestAsync() 的电话。首选后者,因为它将使您的方法保持异步,这在使用资源方面有一些好处。