1

I'm trying to make a post request with the the following code:

string resourceAddress = "url";
string postBody = "jsonbody";
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage x = await httpClient.PostAsync(resourceAddress, new StringContent(postBody, Encoding.UTF8, "application/json"));

I got this compilation error: The 'await' operator can only be used within an async method

Any Ideas? PostAsync returns Task<HttpResponseMessage>...

Christos
  • 53,228
  • 8
  • 76
  • 108
Tomer Z
  • 45
  • 1
  • 6

1 Answers1

2

Your method must be marked as async:

public async ReturnType MethodName()
{
     string resourceAddress = "url";
     string postBody = "jsonbody";
     var httpClient = new HttpClient();
     httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
     HttpResponseMessage x = await httpClient.PostAsync(resourceAddress, new StringContent(postBody, Encoding.UTF8, "application/json"));
}

Not knowing neither the return type of your method nor the method name and it's arguments, I have used vague names and no parameters. You have to replace them with the real one.

Generally, whenever you want to make use of await operator (This is happening when you want to make an asynchronous call), you have to use also the async operator. The async operator is used to denote that you are going to await something. Then the compiler builds for you a state machine that is used by the runtime to execute your code asynchronously.

Christos
  • 53,228
  • 8
  • 76
  • 108