栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何使用C#调用REST api?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何使用C#调用REST api?

ASP.Net Web API取代了前面提到的WCF Web API。

我想我应该发布更新的答案,因为这些回复大多数都来自2012年初,而该线程是在Google搜索“呼叫宁静的服务c#”时的最佳结果之一。

Microsoft当前的指南是使用Microsoft ASP.NET Web
API客户端库来使用RESTful服务。它可以作为NuGet包Microsoft.AspNet.WebApi.Client使用。您将需要将此NuGet软件包添加到您的解决方案中。

使用ASP.Net Web API客户端库实现时,示例如下所示:

using System;using System.Collections.Generic;using System.Net.Http;using System.Net.Http.Headers;namespace ConsoleProgram{    public class DataObject    {        public string Name { get; set; }    }    public class Class1    {        private const string URL = "https://sub.domain.com/objects.json";        private string urlParameters = "?api_key=123";        static void Main(string[] args)        { HttpClient client = new HttpClient(); client.baseAddress = new Uri(URL); // Add an Accept header for JSON format. client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); // List data response. HttpResponseMessage response = client.GetAsync(urlParameters).Result;  // Blocking call! Program will wait here until a response is received or a timeout occurs. if (response.IsSuccessStatusCode) {     // Parse the response body.     var dataObjects = response.Content.ReadAsAsync<IEnumerable<DataObject>>().Result;  //Make sure to add a reference to System.Net.Http.Formatting.dll     foreach (var d in dataObjects)     {         Console.WriteLine("{0}", d.Name);     } } else {     Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase); } //Make any other calls using HttpClient here. //Dispose once all HttpClient calls are complete. This is not necessary if the containing object will be disposed of; for example in this case the HttpClient instance will be disposed automatically when the application terminates so the following call is superfluous. client.Dispose();        }    }}

如果计划发出多个请求,则应重新使用HttpClient实例。有关为什么在这种情况下HttpClient实例上不使用using语句的更多详细信息,请参见此问题及其答案:是否必须处置HttpClient和HttpClientHandler?

有关更多详细信息,包括其他示例,请转到此处:http : //www.asp.net/web-
api/overview/web-api-clients/calling-a-web-api-from-a-net-
client

该博客文章也可能有用:http : //johnnypre.com/2012/02/23/consumption-your-own-
asp-net-web-api-rest-service/



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/465669.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号