我如何(或在哪里)调用我的异步操作方法

时间:2017-05-31 21:13:04

标签: asp.net asp.net-mvc

我对asp和c#相对较新。

我有以下异步操作方法,它调用外部api并返回一个HttpResponseMessage。我希望它在运行时调用Index()动作方法时运行。我曾尝试从Index()内部调用它,但它说Index()也应该是异步的,但我不知道如何使它异步,或者也许我做错了。

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);
                }

            }
        }
    }

1 个答案:

答案 0 :(得分:1)

您的操作方法应返回Task。这允许框架查看方法何时完成。