1

In my c# console application I have a async Task. I want to return a string from it when I run the Task. something is wrong with the way I've written it.

Error Message:

The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.

Below is Code :

static void Main(string[] args)
{        
  string t1 = await DownloadToken(webserverLocal, tokenLocal);
}

static async Task<string> DownloadToken(string server, string token)
{
    using (var client = new HttpClient())
    {
        var url = server + "token";
        var parameters = new Dictionary<string, string> { { "username", usernameMain }, { "password", passwordMain }, { "grant_type", "password" } };
        var encodedContent = new FormUrlEncodedContent(parameters);
        var response = await client.PostAsync(url, encodedContent).ConfigureAwait(false);
        if (response.StatusCode == HttpStatusCode.OK)
        {
            string content = await response.Content.ReadAsStringAsync();
            JToken entireJson = JToken.Parse(content);
            JProperty jName = entireJson.First.Value<JProperty>();
            if (jName.Name == "access_token")
            {
                return jName.Value.ToString();                  
            }
        }
        else
        {
            System.Windows.Forms.MessageBox.Show("ERROR: DownloadToken FAILED!!!", "ERROR");
            Environment.Exit(0);
        }
    }
    return null;
}

The other posts that are similar do not seem to return a string back to the main method.

solarissf
  • 1,199
  • 2
  • 23
  • 58
  • I think there is no need to use `await` inside `Main()` method as you have make use of it in your `async method`. *(Note: `await` can only been used in `async` method)* – Rahul Hendawe Jan 25 '17 at 16:25
  • I also tried string t1 = DownloadToken(webserverLocal, tokenLocal); still errors... also tried .Wait() – solarissf Jan 25 '17 at 16:28
  • try this `DownloadToken(webserverLocal, tokenLocal).Result` insted in your `Main()` method. – Rahul Hendawe Jan 25 '17 at 16:35
  • The duplicate does answer the question, but it is different enough that it may not seem obvious. Your DownloadToken method returns a Task. That Task object has a property called Result. Your string will be there when the task completes. I would provide a simplified example here, but the question has been closed. Take a look at this and see if it helps: https://dotnetfiddle.net/cMZquu – chadnt Jan 25 '17 at 16:41
  • thank you all... the .Result solved it for me. thanks!!! – solarissf Jan 25 '17 at 16:42

0 Answers0