完全迷失在 RestSharp 中

Absolutely lost with RestSharp

我是 C# 的新手,想创建一个具有基本身份验证的 REST Get 请求。 我正在使用 RestSharp,但找不到合适的完整示例。 这是我的代码:

using RestSharp;
using RestSharp.Authenticators;


namespace HttpClientAPP
{
    class Program
    {
        static void Main(string[] args)
        {
            var client = new RestClient("https://data.myhost.de");
            client.Authenticator = new HttpBasicAuthenticator("user", "xxxx");



            var request = new RestRequest("resource",Method.Get);

            client.ExecuteGetAsync(request).Wait();
            
            Console.WriteLine("as");
        }
    }
}

这是我期望的 json 答案,我想解析它以使用数据将其存储在 MYSQL 数据库中:

    {"info": [
      {
      "method": "GET",
      "url": "https://data.myhost.de/zfa-values/{zfaId}",
      "description": "Get a ZFA value by id"
   },
      {
      "method": "GET",
      "url": "https://data.myhost.de/zfa-values",
      "description": "Get a list of available ZFA values"
   },
      {
      "method": "GET",
      "url": "https://data.myhost.de/new-zfa-values",
      "description": "Get a list of available ZFA values which have not been viewed yet"
   },
      {
      "method": "GET",
      "url": "https://data.myhost.de/",
      "description": "Get a list of api endpoints"
   }
]}

如何解析 json 响应?

首先,你可以使用newtosoft json nuget包: 文档:https://www.newtonsoft.com/json

示例:

class ApiEndpoint{
 public string Method {get;set;} // or you can use enum 
 public string Url {get;set;} 
 public string Description {get;set;} 
}
// some logic
public void Fetch()
{
   var client = new RestClient("https://data.myhost.de");
   client.Authenticator = new HttpBasicAuthenticator("user", "xxxx");

   var request = new RestRequest("resource",Method.Get);
   var response = client.Get(request);
   // read response as json
   var json = JsonConvert.DeserializeObject<ICollection<ApiEndpoint>>(response);
   // now json will have structure in your example
}
  1. 其他方法是为你的服务器添加 swagger gen,得到 openapi.json 然后使用 nswag 生成 sharp client https://blog.logrocket.com/generate-typescript-csharp-clients-nswag-api/

https://restsharp.dev/v107/#recommended-usage 有一些指导(但在撰写此答案时我认为它可能有错字)

获取文档说:

public class GitHubClient {
    readonly RestClient _client;

    public GitHubClient() {
        _client = new RestClient("https://api.github.com/")
            .AddDefaultHeader(KnownHeaders.Accept, "application/vnd.github.v3+json");
    }

    public Task<GitHubRepo[]> GetRepos()
        => _client.GetAsync<GitHubRepo[]>("users/aspnet/repos");
                   ^^^^^^^^
        //note: I think this should be GetJsonAsync
}

Post 文档说:

var request = new MyRequest { Data = "foo" };
var response = await _client.PostAsync<MyRequest, MyResponse>(request, cancellationToken);
                             ^^^^^^^^^                        ^^^^^^^
        //note: i think this should be PostJsonAsync      and the first arg should be a string url path

您有 类 代表 json 您 send/get 回来,RestSharp 将为您 de/serialize 他们。如果您需要一些帮助从 JSON 制作 类,请查看 http://app.QuickType.io 之类的服务 - 您粘贴 json 并获得代表 类。在线生成器在 interpret/the 修饰的属性方面通常更复杂一些。将你的 json 粘贴到 QT 中给出(你可以选择一个比 SomeRoot 更好的名字):

namespace SomeNamespace
{
    using System;
    using System.Collections.Generic;

    using System.Globalization;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Converters;

    public partial class SomeRoot
    {
        [JsonProperty("info")]
        public Info[] Info { get; set; }
    }

    public partial class Info
    {
        [JsonProperty("method")]
        public string Method { get; set; }

        [JsonProperty("url")]
        public string Url { get; set; }

        [JsonProperty("description")]
        public string Description { get; set; }
    }

    public partial class SomeRoot
    {
        public static SomeRoot FromJson(string json) => JsonConvert.DeserializeObject<SomeRoot>(json, SomeNamespace.Converter.Settings);
    }

    public static class Serialize
    {
        public static string ToJson(this SomeRoot self) => JsonConvert.SerializeObject(self, SomeNamespace.Converter.Settings);
    }

    internal static class Converter
    {
        public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
        {
            MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
            DateParseHandling = DateParseHandling.None,
            Converters =
            {
                new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
            },
        };
    }
}

并像这样使用:

using RestSharp;
using RestSharp.Authenticators;

namespace HttpClientAPP
{
    class Program
    {
        static async Task Main(string[] args)
        {
            var client = new RestClient("https://data.myhost.de");
            client.Authenticator = new HttpBasicAuthenticator("user", "xxxx");

            var res = await client.GetJsonAsync<SomeRoot>("");

            Console.ReadLine(); //prevent exit
        }
    }
}