简体   繁体   English

在 Task 中分配返回值<String> HttpClient 异步到另一个变量

[英]Assign a return value in Task<String> HttpClient Async to another variable

I'm stuck at casting my return value in a Tast Async function to another variable.我一直在将 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;
        }
    }

How can I assign the value of ip to out of the function?如何将ip的值分配给函数外? For example I want something like below:例如,我想要如下内容:

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

Because your await Task returns a string which is ip, you can just easily call to the previous method as below.因为您的 await 任务返回一个字符串 ip,所以您可以轻松调用前面的方法,如下所示。

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

declare a variable outside of the using scope where you call HttpClient在调用 HttpClient 的 using 范围之外声明一个变量

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

As has been pointed out above in a comment, you should not use the HttpClient in the way you are, but I have answered your question with out a change to the code you are currently using正如上面在评论中指出的那样,您不应该以现在的方式使用 HttpClient,但我已经回答了您的问题,但没有更改您当前使用的代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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