- 상위 문서: 사용자:LOONA
아래는 API를 이용해 문서의 내용을 가져오는 C# 예제 코드다. 닷넷 5.0에서 정상 동작을 확인한 코드의 일부를 구조를 단순화해 적은 것으로, 실제 작동하는 코드와 다를 수 있다.
Json 파싱에 System.Text.Json을 사용했지만 당연히 Newtonsoft.Json을 사용해도 무방하다.
Json Deserialize를 위해 레코드 타입을 이용하기 때문에 9.0 이상 사용을 전제로 한다. 8.X 이하 버전에서 사용한다면 레코드 타입 대신 별도의 클래스를 정의하여 사용해야 한다. JsonDocument로 파싱해 RootElement로부터 Property를 가져오는 방법[1]도 있으나 별도의 Immutable Object를 이용하는 것이 더 적절하다고 본다.
public record ReadDocumentPayload
{
#nullable enable
[JsonPropertyName("text")]
public string? Text { get; init; }
[JsonPropertyName("exists")]
public bool Exists { get; init; }
[JsonPropertyName("token")]
public string? Token { get; init; }
[JsonPropertyName("status")]
public string? Status { get; init; }
#nullable restore
}using System;
using System.Threading.Tasks;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace MyNamespace
{
public class MyClass
{
/* private Field */
private HttpClient _client;
private string _baseUrl = "https://theseed.io/";
private string _token = "My API Token";
/* private Field */
public void InitHttpClient()
{
var handler = new SocketsHttpHandler()
{
AllowAutoRedirect = true,
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
};
this._client = new HttpClient(handler);
this._client.DefaultRequestHeaders.Add("User-Agent", "My User Agent");
this._client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", this._token);
}
public async Task<ReadDocumentPayload> ReadDocumentAsync(string documentName)
{
var url = this._baseUrl + "api/edit/" + documentName;
var response = await this._client.GetAsync(url);
var body = await response.Content.ReadAsStringAsync();
var result = JsonSerializer.Deserialize<ReadDocumentPayload>(body);
if (!string.IsNullOrEmpty(result.Status))
throw new MyException(result.Status);
if(!result.Exists)
throw new MyException("Document does not exist.");
return result;
}
}
}[1] Newtonsoft.Json의 경우 JObject 파싱 후 인덱서로 접근하는 방법