简体   繁体   中英

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.

This is the original Curl Request example that JIRA provides:

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:

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>

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:

protected async Task Foo()

will become

protected void Foo(); 

To return a value, with the async keyword, you should use this signature:

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. A Task<T> on the other hand has a 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.

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. The latter is preferred since it will keep your method async which has some benefits regarding to the use of resources.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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