使用HttpClient调用ASP.NET WebAPI

时间:2016-10-13 11:43:52

标签: c# asp.net asp.net-web-api xamarin.forms

我正在尝试使用HttpClient从我的web api中获取一些值。我设法获得true status。但是,我不知道如何获取值/读取JSON文档。我可以知道是否有办法吗?

我目前正在使用Visual Studio中的Xamarin.Forms。

这是我的代码。

当我在浏览器中输入此URL时,文档如下所示

{"d":[{"__type":"Info:#website.Model","infoClosingHours":"06:00:00 PM","infoID":1,"infoOpeningDays":"Monday","infoOpeningHours":"09:00:00 AM","infoStatus":"Open"}]}

xaml文件

<Button Text="Grab Value" Clicked="GetData"/>

xaml.cs文件

private void GetData(object sender, EventArgs e)
        {
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("ipaddress");

            // Add an Accept header for JSON format.
            client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));

            try{
                HttpResponseMessage response = client.GetAsync("WebServices/information.svc/GetInformationJSON").Result;
                HttpResponseMessage response1 = client.GetAsync("WebServices/information.svc/GetInformationJSON").Result;
            }
            catch
            {

            }

        }

2 个答案:

答案 0 :(得分:2)

如果你的应用程序有任何类似的负载,我建议使用静态HttpClient。否则,您可能会遇到端口耗尽并使服务器瘫痪。请参阅我对使用基于实例的静态HttpClients的响应 - What is the overhead of creating a new HttpClient per call in a WebAPI client?

答案 1 :(得分:0)

您可以像这样使用它:

private async void GetData(object sender, EventArgs e)
{
    using (HttpClient client = new HttpClient())
    {
        client.BaseAddress = new Uri("ipaddress");

        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        try
        {
            HttpResponseMessage response = client.GetAsync("WebServices/information.svc/GetInformationJSON").Result;
            if (response.IsSuccessStatusCode)
            {
                MyObject responseObject = response.Content.ReadAsAsync<MyObject>();
            }
        }
        catch
        {

        }
    }
}

为此,你需要创建一个类&#34; MyObject&#34;它具有JSON-Data中的属性。

也可以将它反序列化为动态对象,如下所示:

private async void GetData(object sender, EventArgs e)
{
    using (HttpClient client = new HttpClient())
    {
        client.BaseAddress = new Uri("ipaddress");

        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        try
        {
            HttpResponseMessage response = client.GetAsync("WebServices/information.svc/GetInformationJSON").Result;
            if (response.IsSuccessStatusCode)
            {
                string jsonString = await response.Content.ReadAsStringAsync();
                dynamic dynamicObject = JsonConvert.DeserializeObject(jsonString);
            }
        }
        catch
        {

        }
    }
}

为此你需要Newtonsoft.Json。