我是C#编程新手。 我想使用openweathermap API开发一个简单的天气应用程序。 我想从URL下载和读取文件的内容。
这是我下载文件内容的代码:
class WebClientToDownload
{
string webresponse;
public async void DownloadFile(string url)
{
string baseurl = "http://api.openweathermap.org/data/2.5/forecast/daily?q=";
StringBuilder sb = new StringBuilder(baseurl);
sb.Append(url + "&mode=json&units=metric&cnt=7");
string actual = sb.ToString();
HttpClient http = new System.Net.Http.HttpClient();
HttpResponseMessage response = await http.GetAsync(actual);
webresponse = await response.Content.ReadAsStringAsync();
}
public string StringReturn()
{
return webresponse;
}
传递给函数的字符串是city的名称。 这是MainPage代码,我称之为这些函数:
string JSONData;
private void GetWeatherButton_Click(object sender, RoutedEventArgs e)
{
WebClientToDownload Cls = new WebClientToDownload();
Cls.DownloadFile(GetWeatherText.Text);
JSONData = Cls.StringReturn();
JSONOutput.Text = JSONData;
}
我在最后一行代码中收到错误,如
An exception of type 'System.ArgumentNullException' occurred in mscorlib.dll but was not handled in user code
Additional information: Value cannot be null.
答案 0 :(得分:1)
看起来好像是等待你的使用。基本上,await会将控制权传递回调用函数并允许它继续运行,直到等待它为止,这在您的情况下不会发生,因此它在返回数据之前调用Cls.StringReturn()。您可以更改如下:
以您的形式:
string JSONData;
// Note the async keyword in the method declaration.
private async void GetWeatherButton_Click(object sender, EventArgs e)
{
WebClientToDownload Cls = new WebClientToDownload();
// Notice the await keyword here which pauses the execution of this method until the data is returned.
JSONData = await Cls.DownloadFile(GetWeatherText.Text);
JSONOutput.Text = JSONData;
}
在您的下载课程中:
class WebClientToDownload
{
// Notice this now returns a Task<string>. This will allow you to await on the data being returned.
public async Task<string> DownloadFile(string url)
{
string baseurl = "http://api.openweathermap.org/data/2.5/forecast/daily?q=";
StringBuilder sb = new StringBuilder(baseurl);
sb.Append(url + "&mode=json&units=metric&cnt=7");
string actual = sb.ToString();
HttpClient http = new System.Net.Http.HttpClient();
HttpResponseMessage response = await http.GetAsync(actual);
// Return the result rather than setting a variable.
return await response.Content.ReadAsStringAsync();
}
}
我已经过测试并返回了有效数据但如果其中任何一项不清楚,请告知我们。