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

后端 未结 15 1777
面向向阳花
面向向阳花 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 08:51

    Here are a few different ways of calling an external API in C# (updated 2019).

    .NET's built-in ways:

    • WebRequest& WebClient - verbose APIs & Microsoft's documentation is not very easy to follow
    • HttpClient - .NET's newest kid on the block & much simpler to use than above.

    Free, open-source NuGet Packages, which frankly have a much better developer experience than .NET's built in clients:

    • ServiceStack.Text (1,000 GitHub stars, 7 million NuGet downloads) (*) - fast, light and resilient.
    • RestSharp (6,000 GitHub stars, 23 million NuGet downloads) (*) - simple REST and HTTP API Client
    • Flurl (1,700 GitHub stars, 3 million NuGet downloads) (*)- a fluent, portable, testable HTTP client library

    All the above packages provide a great developer experience (i.e., concise, easy API) and are well maintained.

    (*) as at August 2019

    Example: Getting a Todo item from a Fake Rest API using ServiceStack.Text. The other libraries have very similar syntax.

    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();
    
            // Print the 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; }
        }
    
    }
    

    Running the above example in a .NET Core Console app, produces the following output.

    Install these packages using NuGet

    Install-Package ServiceStack.Text, or
    
    Install-Package RestSharp, or
    
    Install-Package Flurl.Http
    

提交回复
热议问题