我正在尝试编写一个包含异步函数的类,以使对特定API的Web请求更加简单。为了举例说明我的目标,我希望能够编写如下所示的代码:
private void btnLogin_Click(object sender, RoutedEventArgs e)
{
// Validate Login Details...
// Save login details to xml file if user asks...
JsonObject authSuccess = await myClass.authenticate(username, password); // NOTE JSON WILL BE THE RESPONSE FROM SERVER SO JSONOBJECT SEEMS LOGICAL BUT MAY BE EASIER WAY?
if (authSuccess){
// Go to next part of app...
}else{
// Show error
}
}
private void btnDelete_Click(object sender, RoutedEventArgs e)
{
JsonObject deleteSuccess= await myClass.deleteSomeData(type, data); // NOTE JSON WILL BE THE RESPONSE FROM SERVER SO JSONOBJECT SEEMS LOGICAL BUT MAY BE EASIER WAY?
if (deleteSuccess){
// Go to next part of app...
}else{
// Show error
}
}
myClass看起来像:
namespace myApp
{
public class myClass
{
public async Task<Boolean> authenticate(String username, String apikey)
{
var resp = await PostAsync("http://url", "{\"auth\":{\"passwordCredentials\":{\"username\":\"demouser\",\"password\":\"mypass\"}}}");
return true;
}
public async Task<Boolean> deleteSomeData(String type, String data)
{
var resp = await PostAsync("http://url", "{\"delete\":{\"type\":{\"type\":\"type\",\"data\":\"data\"}}}");
return true;
}
private async Task<JsonObject> PostAsync(string uri, string data)
{
JsonSerializer js = new JsonSerializer();
var httpClient = new HttpClient();
var response = await httpClient.PostAsync(uri, new JsonObject());
response.EnsureSuccessStatusCode();
string content = await response.Content.ReadAsStringAsync();
return await Task.Run(() => JsonObject.Parse(content));
}
}
}
我需要知道是否有一种简单的方法可以做到这一点?我需要能够在我的应用程序的任何地方调用该类,使用PUT,GET,POST,DELETE发送JSON数据与服务器通信,并能够发送自定义标头并设置我自己的内容类型。
我将始终需要能够以json或xml的形式读取和解析服务器的响应。
有人帮忙吗?
PS。很多上面的代码可能都是错误的。
答案 0 :(得分:0)
我通过使用一组扩展方法实现了这一点;
public static bool UpdateItem<TItem>(this HttpClient httpClient, TItem item, string uriBase, string actionName) where TItem : class
{
var response = await httpClient.PutAsJsonAsync(string.Format(uriBase, actionName), item);
response.EnsureSuccessStatusCode();
.
.
.
return success;
}