Error CS4033 - The await Operator and Async Error

lesponce 176 Reputation points
2022-10-11T13:32:59.273+00:00

I’m currently working on a script to get the response values from a cookie. The code below has the following error:

CS4033: The ‘await’ operator can only be used within an async method. Consider making this method with the ’async’ modifier and changing its return type to ‘Task’.

Can you please advise me what I’m missing in the code below? I’m using Visual Studio 2019. Thanks

using System;  
  
  
namespace DummyConsole  
{  
    public partial class Program  
    {  
        static void Main(string[] args)  
        {  
            GetCookie.CheckHeader();  
        }  
    }  
  
}  
  

// GetCookie Class

using System;  
using System.Linq;  
using System.Net;  
using System.Net.Http;  
using System.Threading.Tasks;  
  
namespace DummyConsole  
{  
    public class GetCookie  
    {  
  
        public static void CheckHeader()   
        {  
  
            var myClientHandler = new HttpClientHandler();  
            myClientHandler.CookieContainer = new CookieContainer();  
  
            var client = new HttpClient(myClientHandler);  
  
            var response = await client.GetAsync("https://www.mydomain.com/");   //  <-- He're where I get the error.  
  
            var cookieCollection = myClientHandler.CookieContainer.GetCookies(new Uri("https://www.mydomain.com/"));  
  
            foreach (var cookie in cookieCollection.Cast<Cookie>())  
            {  
                Console.WriteLine(cookie);  
            }  
  
        }  
  
    }  
}  
  
Developer technologies | ASP.NET | ASP.NET Core
Developer technologies | .NET | Other
Developer technologies | C#
0 comments No comments
{count} votes

Accepted answer
  1. AgaveJoe 30,126 Reputation points
    2022-10-11T14:14:01.443+00:00

    The error is very clear and Visual Studio's help feature shows what changes are necessary to make the method async!!!

    public static async Task CheckHeaderAsync()  
    

    Please read the official documentation.

    Asynchronous programming with async and await

    It is not clear what framework you are targeting. You might need the following pattern to invoke the method if an async main() is not available in your targeted framework.

    CheckHeaderAsync().GetAwaiter().GetResult();  
    
    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.