简体   繁体   中英

How (or where) do i call my async action method

I'm relatively new to asp and c#.

I have the following async action method that calls an external api and returns a HttpResponseMessage. I want it to run when the Index() action method is called at runtime. Ive tried calling it from inside Index() but it says that Index() should be async also, but i dont know how to make it async, or maybe im doing it all wrong.

async static void PostRequest(string url, string userID, string accessKey, string djID, string artistName, string artistURL)
    {
        IEnumerable<KeyValuePair<string, string>> queries = new List<KeyValuePair<string, string>>()
        {
            new KeyValuePair<string, string>("UserID", userID),
            new KeyValuePair<string, string>("AccessKey", accessKey),
            new KeyValuePair<string, string>("DJID", djID),
            new KeyValuePair<string, string>("ArtistName", artistName),
            new KeyValuePair<string, string>("URL", artistURL)
        };
        HttpContent q = new FormUrlEncodedContent(queries);

        using (HttpClient client = new HttpClient())
        {
            using (HttpResponseMessage response = await client.PostAsync(url, q))
            {
                using (HttpContent content = response.Content)
                {
                    string myContent = await content.ReadAsStringAsync();
                    HttpContentHeaders headers = content.Headers;
                    System.Diagnostics.Debug.WriteLine(myContent);
                }

            }
        }
    }

Your action method should return Task . This allows the framework to see when the method has completed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM