如何使用C#调用REST API?

Nul*_*uli 303 c# api rest

这是我到目前为止的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System;
using System.Net.Http;
using System.Web;
using System.Net;
using System.IO;

namespace ConsoleProgram
{
    public class Class1
    {
        private const string URL = "https://sub.domain.com/objects.json?api_key=123";
        private const string DATA = @"{""object"":{""name"":""Name""}}";

        static void Main(string[] args)
        {
            Class1.CreateObject();
        }

        private static void CreateObject()
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
            request.Method = "POST";
            request.ContentType = "application/json"; 
            request.ContentLength = DATA.Length;
            StreamWriter requestWriter = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
            requestWriter.Write(DATA);
            requestWriter.Close();

             try {
                WebResponse webResponse = request.GetResponse();
                Stream webStream = webResponse.GetResponseStream();
                StreamReader responseReader = new StreamReader(webStream);
                string response = responseReader.ReadToEnd();
                Console.Out.WriteLine(response);
                responseReader.Close();
            } catch (Exception e) {
                Console.Out.WriteLine("-----------------");
                Console.Out.WriteLine(e.Message);
            }

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是我认为异常块正在被触发(因为当我删除try-catch时,我收到服务器错误(500)消息.但是我没有看到我放在catch块中的Console.Out行.

我的控制台:

The thread 'vshost.NotifyLoad' (0x1a20) has exited with code 0 (0x0).
The thread '<No Name>' (0x1988) has exited with code 0 (0x0).
The thread 'vshost.LoadReference' (0x1710) has exited with code 0 (0x0).
'ConsoleApplication1.vshost.exe' (Managed (v4.0.30319)): Loaded 'c:\users\l. preston sego iii\documents\visual studio 11\Projects\ConsoleApplication1\ConsoleApplication1\bin\Debug\ConsoleApplication1.exe', Symbols loaded.
'ConsoleApplication1.vshost.exe' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Configuration\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Configuration.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
A first chance exception of type 'System.Net.WebException' occurred in System.dll
The thread 'vshost.RunParkingWindow' (0x184c) has exited with code 0 (0x0).
The thread '<No Name>' (0x1810) has exited with code 0 (0x0).
The program '[2780] ConsoleApplication1.vshost.exe: Program Trace' has exited with code 0 (0x0).
The program '[2780] ConsoleApplication1.vshost.exe: Managed (v4.0.30319)' has exited with code 0 (0x0).
Run Code Online (Sandbox Code Playgroud)

我正在使用Visual Studio 2011 Beta和.NET 4.5 Beta.

Bri*_*ift 398

ASP.Net Web API已经取代了之前提到的WCF Web API.

我想我会发布一个更新的答案,因为大多数答案都是从2012年初开始的,这个帖子是Google搜索"call restful service 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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

此博文可能也很有用:http://johnnycode.com/2012/02/23/consuming-your-own-asp-net-web-api-rest-service/

  • 尝试使用但无法使用ReadAsAsync(),得到错误"HttpContent不包含'ReadAsAsync'的定义,也没有扩展方法. (7认同)
  • @RobertGreenMBA:要获取扩展方法`ReadAsAsync()`,请添加对`System.Net.Http.Formatting.dll`的引用.(直观,对吧?) (7认同)
  • 谢谢!我需要安装WebApi客户端NuGet包才能为我工作:Install-Package Microsoft.AspNet.WebApi.Client (6认同)
  • 为了使这个答案比现在更好,你应该将HttpClient声明包装成using语句以更好地管理你的资源:) (5认同)
  • 如果你需要模拟你的REST集成,即使使用客户端库,它仍然不容易.试试RestSharp? (3认同)
  • @DanielSiebert,您可以这样做,但Microsoft建议重复使用相同的实例进行多次调用.请参阅答案中指向asp.net的链接. (3认同)
  • HttpClient的处理详情请看下面的【堆栈溢出问题】(/sf/ask/1099356471/?utm_medium=organic&amp;utm_source=google_rich_qa&amp;utm_campaign =google_rich_qa) (2认同)

Jus*_*ony 117

我的建议是使用RestSharp.您可以调用REST服务并将它们转换为POCO对象,只需很少的样板代码即可实际解析响应.这不会解决您的特定错误,但会回答您关于如何调用REST服务的整体问题.必须更改您的代码才能使用它,应该会在易用性和稳健性方面取得进展.这只是我的2美分

  • RestSharp和JSON.NET绝对是最佳选择.我发现MS工具集缺乏并且可能会失败. (6认同)
  • 请在这个答案中有一个例子. (3认同)
  • RestSharp的另一票选票,因为您可以模拟它进行测试,比WebApi客户端库轻松得多。 (2认同)
  • 缺少示例使这篇文章没有帮助! (2认同)

Jes*_*cer 33

不确定,我敢肯定,但是要把你的IDisposable物品包裹起来using以确保妥善处理:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System;
using System.Web;
using System.Net;
using System.IO;

namespace ConsoleProgram
{
    public class Class1
    {
        private const string URL = "https://sub.domain.com/objects.json?api_key=123";
        private const string DATA = @"{""object"":{""name"":""Name""}}";

        static void Main(string[] args)
        {
            Class1.CreateObject();
        }

        private static void CreateObject()
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
            request.Method = "POST";
            request.ContentType = "application/json";
            request.ContentLength = DATA.Length;
            using (Stream webStream = request.GetRequestStream())
            using (StreamWriter requestWriter = new StreamWriter(webStream, System.Text.Encoding.ASCII))
            {
                requestWriter.Write(DATA);
            }

            try
            {
                WebResponse webResponse = request.GetResponse();
                using (Stream webStream = webResponse.GetResponseStream() ?? Stream.Null)
                using (StreamReader responseReader = new StreamReader(webStream))
                {
                    string response = responseReader.ReadToEnd();
                    Console.Out.WriteLine(response);
                }
            }
            catch (Exception e)
            {
                Console.Out.WriteLine("-----------------");
                Console.Out.WriteLine(e.Message);
            }

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 很好的答案,不使用常规.NET环境之外的任何额外的包. (4认同)
  • 因为找不到资源?获得 404 的原因有很多。 (3认同)

小智 17

请使用以下代码来获取REST api请求

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Json;

namespace ConsoleApplication2
{
    class Program
    {
        private const string URL = "https://XXXX/rest/api/2/component";
        private const string DATA = @"{
    ""name"": ""Component 2"",
    ""description"": ""This is a JIRA component"",
    ""leadUserName"": ""xx"",
    ""assigneeType"": ""PROJECT_LEAD"",
    ""isAssigneeTypeValid"": false,
    ""project"": ""TP""}";

        static void Main(string[] args)
        {
            AddComponent();
        }

        private static void AddComponent()
        {
            System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
            client.BaseAddress = new System.Uri(URL);
            byte[] cred = UTF8Encoding.UTF8.GetBytes("username:password");
            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(cred));
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

            System.Net.Http.HttpContent content = new StringContent(DATA, UTF8Encoding.UTF8, "application/json");
            HttpResponseMessage messge = client.PostAsync(URL, content).Result;
            string description = string.Empty;
            if (messge.IsSuccessStatusCode)
            {
                string result = messge.Content.ReadAsStringAsync().Result;
                description = result;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @JCKödel-您并非绝对在这里,应该阅读以下内容https://stackoverflow.com/a/22561368-HttpClient旨在重新用于多个呼叫 (5认同)

Pro*_*ark 13

这是使用C#调用外部API(2019年更新)的几种不同方式。

.NET的内置方式:

免费的开源NuGet软件包,坦率地说,它具有比.NET内置客户端更好的开发人员体验:

  • ServiceStack.Text(1k github星,7m Nuget下载)(*)-快速,轻便且具有弹性。
  • RestSharp(6k github星级,23m Nuget下载)(*)-简单的REST和HTTP API客户端
  • Flurl1.7k github stars,3m Nuget Downloads)(*)-一个流畅,可移植,可测试的HTTP客户端库

以上所有软件包均提供了出色的开发人员体验(即简洁,易于使用的API),并且维护良好。

(*)截至2019年8月

示例:使用ServiceStack.Text从Fake Rest API获取待办事项。 其他库具有非常相似的语法。

class Program
{
    static void Main(string[] args)
    {
        // fake rest API
        string url = "https://jsonplaceholder.typicode.com/todos/1";

        // GET data from api & map to Poco
        var todo =  url.GetJsonFromUrl().FromJson<Todo>();

        // print result to screen
        todo.PrintDump();
    }
    public class Todo
    {
        public int UserId { get; set; }
        public int Id { get; set; }
        public string Title { get; set; }
        public bool Completed { get; set; }
    }

}
Run Code Online (Sandbox Code Playgroud)

在.NET Core控制台应用程序中运行上述示例,将产生以下输出。

在此处输入图片说明

使用NuGet安装这些软件包

Install-Package ServiceStack.Text, or

Install-Package RestSharp, or

Install-Package Flurl.Http
Run Code Online (Sandbox Code Playgroud)

  • @Tomasz - ServiceStack.Text 和上面显示的 HttpUtils 是免费的开源 https://github.com/ServiceStack/ServiceStack.Text。 (2认同)

Dal*_*oft 9

使用.NET 4.5或.NET Core时调用REST API的更新

我会建议DalSoft.RestClient(我创建它的警告).原因是因为它使用动态类型,您可以在一个流畅的调用中包含所有内容,包括序列化/反序列化.下面是一个有效的PUT示例:

dynamic client = new RestClient("http://jsonplaceholder.typicode.com");

var post = new Post { title = "foo", body = "bar", userId = 10 };

var result = await client.Posts(1).Put(post);
Run Code Online (Sandbox Code Playgroud)


Ras*_*kov 7

我想在ASP.NET Core中分享我的解决方案

using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;

namespace WebApp
{
    public static class HttpHelper
    {
        // In my case this is https://localhost:44366/
        private static readonly string apiBasicUri = ConfigurationManager.AppSettings["apiBasicUri"];

        public static async Task Post<T>(string url, T contentValue)
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(apiBasicUri);
                var content = new StringContent(JsonConvert.SerializeObject(contentValue), Encoding.UTF8, "application/json");
                var result = await client.PostAsync(url, content);
                result.EnsureSuccessStatusCode();
            }
        }

        public static async Task Put<T>(string url, T stringValue)
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(apiBasicUri);
                var content = new StringContent(JsonConvert.SerializeObject(stringValue), Encoding.UTF8, "application/json");
                var result = await client.PutAsync(url, content);
                result.EnsureSuccessStatusCode();
            }
        }

        public static async Task<T> Get<T>(string url)
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(apiBasicUri);
                var result = await client.GetAsync(url);
                result.EnsureSuccessStatusCode();
                string resultContentString = await result.Content.ReadAsStringAsync();
                T resultContent = JsonConvert.DeserializeObject<T>(resultContentString);
                return resultContent;
            }
        }

        public static async Task Delete(string url)
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(apiBasicUri);
                var result = await client.DeleteAsync(url);
                result.EnsureSuccessStatusCode();
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

要发布,请使用以下内容:

await HttpHelper.Post<Setting>($"/api/values/{id}", setting);
Run Code Online (Sandbox Code Playgroud)

删除示例:

await HttpHelper.Delete($"/api/values/{id}");
Run Code Online (Sandbox Code Playgroud)

获取列表的示例:

List<ClaimTerm> claimTerms = await HttpHelper.Get<List<ClaimTerm>>("/api/values/");
Run Code Online (Sandbox Code Playgroud)

仅获得一个示例:

ClaimTerm processedClaimImage = await HttpHelper.Get<ClaimTerm>($"/api/values/{id}");
Run Code Online (Sandbox Code Playgroud)

  • 这是一段非常好的代码,尽管您不应该在 using 块内使用 httpclient。请参阅https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/ (3认同)

pat*_*ley 6

查看Refit以从 .NET 调用 REST 服务。我发现它非常容易使用:

Refit:适用于 .NET Core、Xamarin 和 .NET 的自动类型安全 REST 库

Refit 是一个深受 Square 的 Retrofit 库启发的库,它将您的 REST API 转变为实时界面:

public interface IGitHubApi {
        [Get("/users/{user}")]
        Task<User> GetUser(string user);
}

// The RestService class generates an implementation of IGitHubApi
// that uses HttpClient to make its calls:

var gitHubApi = RestService.For<IGitHubApi>("https://api.github.com");

var octocat = await gitHubApi.GetUser("octocat");
Run Code Online (Sandbox Code Playgroud)


Jer*_*yal 5

得到:

// GET JSON Response
public WeatherResponseModel GET(string url) {
    WeatherResponseModel model = new WeatherResponseModel();
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    try {
        WebResponse response = request.GetResponse();
        using(Stream responseStream = response.GetResponseStream()) {
            StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
            model = JsonConvert.DeserializeObject < WeatherResponseModel > (reader.ReadToEnd());
        }
    } catch (WebException ex) {
        WebResponse errorResponse = ex.Response;
        using(Stream responseStream = errorResponse.GetResponseStream()) {
            StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
            String errorText = reader.ReadToEnd();
            // log errorText
        }
        throw;
    }

    return model;
}
Run Code Online (Sandbox Code Playgroud)

开机自检:

// POST a JSON string
void POST(string url, string jsonContent) {
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    request.Method = "POST";

    System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
    Byte[]byteArray = encoding.GetBytes(jsonContent);

    request.ContentLength = byteArray.Length;
    request.ContentType =  @ "application/json";

    using(Stream dataStream = request.GetRequestStream()) {
        dataStream.Write(byteArray, 0, byteArray.Length);
    }
    long length = 0;
    try {
        using(HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
            // got response
            length = response.ContentLength;
        }
    } catch (WebException ex) {
        WebResponse errorResponse = ex.Response;
        using(Stream responseStream = errorResponse.GetResponseStream()) {
            StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
            String errorText = reader.ReadToEnd();
            // log errorText
        }
        throw;
    }
}
Run Code Online (Sandbox Code Playgroud)

注意:为了序列化和反序列化JSON,我使用了Newtonsoft.Json NuGet包。