【问题标题】:How to call web API in WPF 4.0如何在 WPF 4.0 中调用 Web API
【发布时间】:2013-09-05 08:14:13
【问题描述】:

我想在我的 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 中的同一种解决方案

请帮帮我

【问题讨论】:

    标签: asp.net .net json rest wpf-4.0


    【解决方案1】:

    您必须安装 NuGet 包管理器和 Http 客户端库。这应该有效: http://www.codeproject.com/Articles/611176/CallingplusASP-NetplusWebAPIplususingplusHttpClien

    【讨论】:

    • 亲爱的 Chevul Ervin,我尝试安装 Http 客户端库,但显示错误,就像它只需要 .Net 4.5 版本一样。
    • 是的,你是对的,很抱歉,我也没有时间测试这个,可能我稍后会做,但以下链接可能是答案:johnnycode.com/2012/02/23/…
    【解决方案2】:
     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;
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-13
      • 2020-10-13
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-08
      相关资源
      最近更新 更多