簡體   English   中英

c#異步卷曲請求 - 如何訪問響應?

[英]c# Async curl request - how do I access the response?

我正在嘗試將來自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;
        }
    }
}

你應該返回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;

由於async關鍵字,方法范圍內的方法簽名(如編譯器所見)將被轉換:

protected async Task Foo()

會變成

protected void Foo(); 

要使用async關鍵字返回值,您應該使用此簽名:

protected async Task<T> Foo()

結果

protected T Foo()

對於呼叫者,簽名保持不變。

Task ,未定義Result因為它本質上沒有來自任務的返回值。 另一方面, Task<T> 具有 Result

因此,為了獲得“結果”,( Result未在Task定義( Wait ),您應該使用Task<T> ,在其上定義Result

在您的情況下,您應該將簽名更改為:

protected async System.Threading.Tasks.Task<WhatEverTypeYouAreReturning> curlRequestAsync()

如果您處於異步范圍內,您現在可以獲取Resultawait呼叫。 后者是首選,因為它會使您的方法保持異步,這對資源的使用有一些好處。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM