r4
r1
1 * 상위 문서: [[사용자:LOONA]]
2
3아래는 [[https://doc.theseed.io/#the-seed-engine-api|API]]를 이용해 문서의 내용을 가져오는 C# 예제 코드다. 닷넷 5.0에서 동작하는 코드의 일부를 구조를 단순화해 적은 것으로, 실제 동작하는 코드와 다를 수 있다.
4
5Json 파싱에 System.Text.Json을 사용했지만 당연히 Newtonsoft.Json을 사용해도 무방하다.
6
r3
7레코드 타입을 이용하기 때문에 9.0 이상 사용을 전제로 한다. 8.X 이하 버전에서 사용한다면 레코드 타입 대신 별도의 클래스를 정의하여 사용해야 한다.
r1
8
9Json Deserialize를 위해 레코드 타입을 추가한다. JsonDocument로 파싱해 RootElement로부터 Property를 가져오는 방법도 있으나 별도의 Immutable Object를 이용하는 것이 더 적절하다고 본다.
10{{{#!syntax csharp
11public record ReadDocumentPayload
12{
13#nullable enable
14 [JsonPropertyName("text")]
15 public string? Text { get; init; }
16 [JsonPropertyName("exists")]
17 public bool Exists { get; init; }
18 [JsonPropertyName("token")]
19 public string? Token { get; init; }
20 [JsonPropertyName("status")]
21 public string? Status { get; init; }
22#nullable restore
23}
24}}}
25{{{#!syntax csharp
26using System;
27using System.Threading.Tasks;
28using System.Net;
29using System.Net.Http;
30using System.Text.Json;
31
32namespace MyNamespace
33{
34 public class MyClass
35 {
36 /* private Field */
37 private HttpClient _client;
38 private string _baseUrl = "https://theseed.io/";
39 private string _token = "My API Token";
40 /* private Field */
41
42 public void InitHttpClient()
43 {
44 var handler = new SocketsHttpHandler()
45 {
46 AllowAutoRedirect = true,
47 AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
48 };
49 this._client = new HttpClient(handler);
50 this._client.DefaultRequestHeaders.Add("User-Agent", "My User Agent");
51 this._client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", this._token);
52 }
53
r2
54 public async Task<ReadDocumentPayload> ReadDocumentAsync(string documentName)
r1
55 {
56 var url = this._baseUrl + "api/edit/" + documentName;
r4
57 var response = await this._client.GetAsync(url);
r1
58 var body = await response.Content.ReadAsStringAsync();
59
60 var result = JsonSerializer.Deserialize<ReadDocumentPayload>(body);
61
62 if (!string.IsNullOrEmpty(result.Status))
63 throw new MyException(result.Status);
64 if(!result.Exists)
65 throw new MyException("Document does not exist.");
66
67 return result;
68 }
69 }
70}
71}}}