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>...

1
  • 1
    Well, is your method async? Commented May 2, 2016 at 22:10

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@TomerZvirsh You are welcome. I am glad that I helped.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.