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