简体   繁体   English

c#异步卷曲请求 - 如何访问响应?

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

I'm trying to convert a curl request example from an API for Jira into a C# request. 我正在尝试将来自Jira的API的curl请求示例转换为C#请求。

This is the original Curl Request example that JIRA provides: 这是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

Which I've translated into the below code for JIRA: 我已将其翻译成以下JIRA代码:

However the response lines don't work - because I've cobbled together a few examples and got a bit stuck! 然而,响应线不起作用 - 因为我拼凑了几个例子并且有点卡住了!

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!

Any help would be appreciated as I'm really stuck! 任何帮助都会受到赞赏,因为我真的被卡住了!

Full example: 完整示例:

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;
        }
    }
}

you should return Task<System.Net.Http.HttpResponseMessage> 你应该返回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;
    }
}

after that you could access response of your task: 之后,您可以访问您的任务的响应:

var myTask = curlRequestAsync();

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

Due to the async keyword, your methods signature, as "seen by the compiler", within the methods's scope is converted: 由于async关键字,方法范围内的方法签名(如编译器所见)将被转换:

protected async Task Foo()

will become 会变成

protected void Foo(); 

To return a value, with the async keyword, you should use this signature: 要使用async关键字返回值,您应该使用此签名:

protected async Task<T> Foo()

which results in 结果

protected T Foo()

As for the caller , the signature stays the same. 对于呼叫者,签名保持不变。

On Task , Result is not defined because by its nature it doesn't have a return value from the task. Task ,未定义Result因为它本质上没有来自任务的返回值。 A Task<T> on the other hand has a Result . 另一方面, Task<T> 具有 Result

So, in order to get an "result", ( Result is not defined on Task ( Wait is), you should use Task<T> , on which Result is defined. 因此,为了获得“结果”,( Result未在Task定义( Wait ),您应该使用Task<T> ,在其上定义Result

In your case you should change the signature to: 在您的情况下,您应该将签名更改为:

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

You will now able to get the Result or await the call if you are in an async scope. 如果您处于异步范围内,您现在可以获取Resultawait呼叫。 The latter is preferred since it will keep your method async which has some benefits regarding to the use of resources. 后者是首选,因为它会使您的方法保持异步,这对资源的使用有一些好处。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM