繁体   English   中英

使用HttpClient调用ASP.NET WebAPI

[英]Calling ASP.NET WebAPI using HttpClient

我正在尝试使用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
            {

            }

        }

如果您的应用程序有任何种类的负载,我建议使用静态HttpClient。 否则,您可能会遇到端口耗尽的问题,并使服务器瘫痪。 请参阅有关使用基于实例的HttpHttps和静态HttpClients的响应- 在WebAPI客户端中的每次调用中创建新的HttpClient的开销是多少?

您可以这样使用它:

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
        {

        }
    }
}

为此,您需要创建一个类“ MyObject”,该类具有JSON-Data中的Properties。

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

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。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM