How do I make calls to a REST API using C#?

后端 未结 15 1861
面向向阳花
面向向阳花 2020-11-22 08:10

This is the code I have so far:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System;
using System.Net.Http;
usi         


        
15条回答
  •  天命终不由人
    2020-11-22 09:01

    The ASP.NET Web API has replaced the WCF Web API previously mentioned.

    I thought I'd post an updated answer since most of these responses are from early 2012, and this thread is one of the top results when doing a Google search for "call restful service C#".

    Current guidance from Microsoft is to use the Microsoft ASP.NET Web API Client Libraries to consume a RESTful service. This is available as a NuGet package, Microsoft.AspNet.WebApi.Client. You will need to add this NuGet package to your solution.

    Here's how your example would look when implemented using the ASP.NET Web API Client Library:

    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>().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();
            }
        }
    }
    

    If you plan on making multiple requests, you should re-use your HttpClient instance. See this question and its answers for more details on why a using statement was not used on the HttpClient instance in this case: Do HttpClient and HttpClientHandler have to be disposed between requests?

    For more details, including other examples, see Call a Web API From a .NET Client (C#)

    This blog post may also be useful: Using HttpClient to Consume ASP.NET Web API REST Services

提交回复
热议问题