从C#调用REST API

SMT*_*SMT 1 c# rest

我在JAVA中开发了基于REST的API.现在我试图从基于控制台的C#应用​​程序调用该API,即从它的主要功能.我想知道是否可以这样做.我尝试了一些东西,但它不起作用

//我在我的类文件中写了下面的代码.但是我找不到RestClient类.我需要包括这个

static void Main(string[] args)
        {
             {

                 string endPoint = @"http:\\myRestService.com\api\";
                 var client = new RestClient(endPoint);
                 var json = client.MakeRequest();
              }
         }
Run Code Online (Sandbox Code Playgroud)

Tho*_*ins 5

来自asp.net网站上的文档.这显示了它是如何在C#中完成的,你尝试使用的RestClient是一个lib,它封装了类似这样的东西.RestClient可以作为块包添加.

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace ProductStoreClient
{
    class Product
    {
        public string Name { get; set; }
        public double Price { get; set; }
        public string Category { get; set; }
    }

    class Program
    {
        static void Main()
        {
            RunAsync().Wait();
        }

        static async Task RunAsync()
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://localhost:9000/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                // HTTP GET
                HttpResponseMessage response = await client.GetAsync("api/products/1");
                if (response.IsSuccessStatusCode)
                {
                    Product product = await response.Content.ReadAsAsync<Product>();
                    Console.WriteLine("{0}\t${1}\t{2}", product.Name, product.Price, product.Category);
                }

                // HTTP POST
                var gizmo = new Product() { Name = "Gizmo", Price = 100, Category = "Widget" };
                response = await client.PostAsJsonAsync("api/products", gizmo);
                if (response.IsSuccessStatusCode)
                {
                    Uri gizmoUrl = response.Headers.Location;

                    // HTTP PUT
                    gizmo.Price = 80;   // Update price
                    response = await client.PutAsJsonAsync(gizmoUrl, gizmo);

                    // HTTP DELETE
                    response = await client.DeleteAsync(gizmoUrl);
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)