简体   繁体   English

异步方法不返回字符串

[英]Async Method not Returning a String

I am trying to get some weather data from Open Weather Maps and l use HTTPClient and API ASP.NET in C#.我正在尝试从 Open Weather Maps 获取一些天气数据,并在 C# 中使用 HTTPClient 和 API ASP.NET。 My code keeps returning:我的代码不断返回:

System.Threading.Tasks.Task`1[System.String] System.Threading.Tasks.Task`1[System.String]

I've made my methods async and await but I still get the above returned.我已经使我的方法asyncawait但我仍然得到上述返回。 I thought making it await would return the value.我认为让它await会返回值。

I am just trying to get the string from Open Weather Maps, I'll worry about parsing it to JSON once I have this working.我只是想从 Open Weather Maps 中获取字符串,一旦我开始工作,我就会担心将其解析为 JSON。 Here is my code, "MY_APPID" is replaced with my API key, I just removed it here.这是我的代码,“MY_APPID”替换为我的 API 密钥,我只是在此处将其删除。

My main:我的主要:

private async Task<string> GetLocationJson()
    {
        const string APPID = "(MY_APPID)";
        const string LOCATIONID = "2172797";
        string jsonAsString = ""; 
        string callStringJson = "api.openweathermap.org/data/2.5/weather?id=" + LOCATIONID + "&appid=" + APPID;

        ApiCalls weatherApi = new ApiCalls(callStringJson);
        jsonAsString = await weatherApi.GetLocationJson();
        return jsonAsString;
    }

    //ShowLocationJson is called on button click
    protected void ShowLocationJson(object sender, EventArgs e)
    {           
        litOutput.Text = GetLocationJson().ToString();
    }

And my ApiCalls Class is:我的 ApiCalls 类是:

public class ApiCalls
{

    HttpClient client = new HttpClient();
    Uri url;
    
    public ApiCalls(string link)
    {
        url = new Uri("https://" + link);            
    }

    public async Task<string> GetLocationJson()
    {
        string content = await client.GetStringAsync(url);
        return content;
    }
}

url variable is being passed the correct values so I know it's ok up to there. url变量正在传递正确的值,所以我知道到那里没问题。

Im using ASP.NET Framework 4.5 as well我也在使用 ASP.NET Framework 4.5

As Steve and mason have already noticed you have to await all methods returning Task.正如史蒂夫和梅森已经注意到的那样,您必须等待所有返回 Task 的方法。 You need to change your ShowLocationMethod to:您需要将 ShowLocationMethod 更改为:

protected async void ShowLocationJson(object sender, EventArgs e)
{           
    litOutput.Text = await GetLocationJson();
}

You receive System.Threading.Tasks.Task1[System.String] because you call method ToString() of Task object.您收到System.Threading.Tasks.Task1[System.String]因为您调用了 Task 对象的 ToString() 方法。 The default implementation of the ToString method returns the fully qualified name of the type of the object: Task<String> ToString方法的默认实现返回对象类型的完全限定名称: Task<String>

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

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