所以我只是尝试制作一个应用程序,按一个按钮并关闭灯。简单吧?但是我很傻。
因此,我以前从未玩过Web API(或其他任何api)。我正在追踪This MS Doc来掌握它。对其进行修改以使其正常运行,但是(显然没有)。
在Button_Click中,出现RunUpdate错误'MainPage.Runupdate()'是一种方法,在给定的上下文中不无效'
这可能是一个简单的解决方法,但我肯定会遇到更多。有人帮我吗? 谢谢!
代码如下:
public sealed partial class MainPage : Page
{
static HttpClient client = new HttpClient();
public class Light
{
//public string ID { get; set }
public string Name { get; set; }
public string state { get; set; }
}
public MainPage()
{
this.InitializeComponent();
client.BaseAddress = new Uri("http://192.168.0.100/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
}
static async Task<Light> GetLightAsync(string path)
{
Light light = null;
HttpResponseMessage response = await client.GetAsync(path);
if(response.IsSuccessStatusCode)
{
light = await response.Content.ReadAsAsync<Light>();
}
return light;
}
static async Task<Light> UpdateLightAsync(Light light)
{
HttpResponseMessage response = await client.PutAsJsonAsync(
$"api/api/RjplsYoXQvdTl11DOVIo92SKNB7vYRfwZvqCzvDK/lights/1/state/", light.state);
response.EnsureSuccessStatusCode();
light = await response.Content.ReadAsAsync<Light>();
return light;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
RunUpdate.GetAwaiter().GetResult();
}
static async Task RunUpdate()
{
Light light = new Light { Name = "Unknown", state = "off" };
light = await UpdateLightAsync(light);
}
}
答案 0 :(得分:1)
好吧,RunUpdate()是一种方法-您从Button_Click中忘记了RunUpdate调用中的括号:)