Question How do I Return Data from Task<IRestResponse>

Jo15765

Member
Joined
May 1, 2018
Messages
6
Programming Experience
Beginner
Hello All ----
How can I return my return await response.StatusCode;?

Here is the code....
C#:
public async Task<IRestResponse> HitAPI(JsonData jsonSend) {
    var client = new RestClient("");
    var request = new RestRequest("", Method.Post);
    
    request.AddParameter("application/json; charset=utf-8", jsonSend, ParameterType.RequestBody);
    request.RequestFormat = DataFormat.Json;

    client.ExecuteAsync(request, response =>
                        {
                            if (response.StatusCode == System.Net.HttpStatusCode.Ok)
                            {
                                //it work
                            }
                            else
                            {
                                //no work
                            }
                        });
    
    return await response.StatusCode;
}
 
Last edited by a moderator:
First things first, code is not a list. It is code. Please use the CODE tool rather than the LIST tool to format it. As you can see, it's rather more readable. Also, please post code that compiles. We should have to modify your code and hope we got it right in order to test it. If you possibly can, edit your code in VS and then copy and paste, rather than editing it after pasting it. You will make fewer errors that way.
 
As for the question, I haven't used RestSharp (which I'm guessing is what you're using but we shouldn't have to guess) but, from what I can see, you should be doing this:
C#:
var response = await client.ExecuteAsync(request);
if you want to access the response in the main body of your method.

Also, I think response is type IRestResponse, so you need to either return the response itself or change the return type of your method to the type of what you want to return.
 
As general advice, you probably need to spend some time learning the general principles involved with using async/await rather than just diving in to using a library that does its work asynchronously and hoping to pick up what you need.
 
Back
Top Bottom