将Task <string> HttpClient Async中的返回值分配给另一个变量

时间:2018-02-07 16:53:29

标签: c# asynchronous

我坚持将Tast Async函数中的返回值转换为另一个变量。

           using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
            client.BaseAddress = new Uri("https://foo.com");
            await GetSecret(client);
        }
    }

    public static async Task<String> GetSecret(HttpClient client)
    {
        //JArray results = new JArray();
        string url = $"/strkey?api-version=2016-10-01";

        using (var httpResponse = await client.GetAsync(url))
        {
            httpResponse.EnsureSuccessStatusCode();
            string responsContent = await httpResponse.Content.ReadAsStringAsync();
            JObject password = JObject.Parse(responsContent);
            string ip = password["value"].ToString();
            return ip;
        }
    }

如何将 ip 的值分配给该功能?例如,我想要下面的内容:

public class objA
{
    public string key { get; set; }
    public objA(string ip)
    {
        key = ip;
    }
}

2 个答案:

答案 0 :(得分:1)

因为你的await Task返回一个ip字符串,你可以轻松调用上面的方法,如下所示。

static async Task yourMethod(HttpClient client)
        {
            var obj = await GetSecret(client);
            Console.WriteLine(obj);
        }

答案 1 :(得分:-1)

在您调用HttpClient

的使用范围之外声明一个变量
    public void MethodName()
    {
        var returnedIp = "";
        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
            client.BaseAddress = new Uri("https://foo.com");
            returnedIp = await GetSecret(client);
        }
    }

正如上面在评论中指出的那样,你不应该像你一样使用HttpClient,但是我已经回答了你的问题而没有更改你当前使用的代码