我想在我的 WPF 4.0 应用程序中调用 Web API,其中 API 以 JSON 格式接收请求并以 JSON 格式发送响应。
我从这里得到了在 WPF 4.5 中调用 Web API的解决方案http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-wpf-application
但我想要 WPF 4.0 中的同一种解决方案
请帮我
您必须安装 NuGet 包管理器和 Http 客户端库。这应该工作: http: //www.codeproject.com/Articles/611176/CallingplusASP-NetplusWebAPIplususingplusHttpClien
public T CallWebAPi<T>(string userName, string password, Uri url, out bool isSuccessStatusCode)
{
T result = default(T);
using (HttpClient client = new HttpClient())
{
client.BaseAddress = url;
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", userName, password))));
HttpResponseMessage response = client.GetAsync(url).Result;
isSuccessStatusCode = response.IsSuccessStatusCode;
var JavaScriptSerializer = new JavaScriptSerializer();
if (isSuccessStatusCode)
{
var dataobj = response.Content.ReadAsStringAsync();
result = JavaScriptSerializer.Deserialize<T>(dataobj.Result);
}
else if (Convert.ToString(response.StatusCode) != "InternalServerError")
{
result = JavaScriptSerializer.Deserialize<T>("{ \"APIMessage\":\"" + response.ReasonPhrase + "\" }");
}
else
{
result = JavaScriptSerializer.Deserialize<T>("{ \"APIMessage\":\"InternalServerError\" }");
}
}
return result;
}