53 lines
1.8 KiB
C#
53 lines
1.8 KiB
C#
|
|
using System.Net.Http.Json;
|
|||
|
|
using Volo.Abp.Settings;
|
|||
|
|
|
|||
|
|
namespace Sozsoft.Sender;
|
|||
|
|
|
|||
|
|
/// <summary>
|
|||
|
|
/// Sağlayıcı istemcilerinin ortak iskeleti: <see cref="IHttpClientFactory"/> ile verilen
|
|||
|
|
/// <see cref="HttpClient"/>, ayarlardan okunan uç nokta ve JSON gövde ile POST. Sağlayıcıya özgü
|
|||
|
|
/// olan yalnızca istek gövdesi, başlıklar ve cevap tipidir.
|
|||
|
|
/// </summary>
|
|||
|
|
public abstract class SettingHttpClientBase : IDisposable
|
|||
|
|
{
|
|||
|
|
protected HttpClient HttpClient { get; }
|
|||
|
|
protected ISettingProvider SettingProvider { get; }
|
|||
|
|
|
|||
|
|
protected SettingHttpClientBase(HttpClient httpClient, ISettingProvider settingProvider)
|
|||
|
|
{
|
|||
|
|
HttpClient = httpClient;
|
|||
|
|
SettingProvider = settingProvider;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
protected Task<string?> GetSettingAsync(string name) => SettingProvider.GetOrNullAsync(name);
|
|||
|
|
|
|||
|
|
/// <summary>
|
|||
|
|
/// Gövdeyi JSON olarak gönderir ve cevabı <typeparamref name="TResponse"/> olarak okur.
|
|||
|
|
/// <paramref name="ensureSuccess"/> kapalıyken 4xx gövdesi de okunur: bazı API'ler hatayı
|
|||
|
|
/// durum koduyla değil gövdedeki açıklamayla verir.
|
|||
|
|
/// </summary>
|
|||
|
|
protected async Task<TResponse?> PostJsonAsync<TResponse>(
|
|||
|
|
string url,
|
|||
|
|
object body,
|
|||
|
|
Action<HttpRequestMessage>? configureRequest = null,
|
|||
|
|
bool ensureSuccess = false)
|
|||
|
|
{
|
|||
|
|
using var request = new HttpRequestMessage(HttpMethod.Post, url) { Content = JsonContent.Create(body) };
|
|||
|
|
configureRequest?.Invoke(request);
|
|||
|
|
|
|||
|
|
using var response = await HttpClient.SendAsync(request);
|
|||
|
|
if (ensureSuccess)
|
|||
|
|
{
|
|||
|
|
response.EnsureSuccessStatusCode();
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
return await response.Content.ReadFromJsonAsync<TResponse>();
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
public void Dispose()
|
|||
|
|
{
|
|||
|
|
HttpClient.Dispose();
|
|||
|
|
GC.SuppressFinalize(this);
|
|||
|
|
}
|
|||
|
|
}
|