Buy Me A Coffee

Basit Bir Rest Api Client Geliştirelim 8

2023-05-12

Bu noktada, geliştirmemiz gereken bir diğer önemli konu da güvenlikle ilgili olabilir. Özellikle, API çağrıları genellikle belirli bir kimlik doğrulama yöntemi gerektirir. Bunu sağlamak için, HTTP istemcimizi çok kullanılan iki kimlik doğrulama yöntemiyle, yani Basic Authentication ve Bearer (Token) Authentication ile uyumlu hale getirebiliriz.

Bu amaçla, istemcimize iki yeni metot ekleyelim:

public void SetBasicAuthentication(string username, string password)
{
    var basicAuthValue = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{username}:{password}"));
    SetDefaultHeader("Authorization", $"Basic {basicAuthValue}");
}

public void SetBearerToken(string token)
{
    SetDefaultHeader("Authorization", $"Bearer {token}");
}

Bu metodlar, Authorization başlığını ayarlar, böylece her HTTP talebi kimlik doğrulama bilgilerini içerir. SetBasicAuthentication metodu, kullanıcı adı ve parola kullanarak Basic Authentication ayarlar. SetBearerToken metodu ise bir Bearer Token ayarlar.

Bu özellikler, HTTP istemcimizin çeşitli kimlik doğrulama yöntemlerini desteklemesini sağlar, böylece daha geniş bir dizi API ile çalışabilir.

Bir sonraki adım olarak HTTP yanıtlarının daha kapsamlı bir şekilde işlenmesi olabilir. Bu, yanıtların HTTP durum kodlarına ve içerik türlerine göre farklı şekillerde işlenmesini içerir. Örneğin, bir yanıt 404 Not Found durum kodunu içeriyorsa, bu durumu belirli bir şekilde işlemek isteyebiliriz. Ayrıca, bir yanıtın içeriği belirli bir MIME türüne (örneğin, “application/json” veya “text/plain”) sahipse, bu içeriği belirli bir şekilde işlemek isteyebiliriz.

Bu tür bir işlevselliği desteklemek için, SendRequestAsync metodunu genişletebiliriz:

public async Task<T> SendRequestAsync<T>(string uri, HttpMethod method, object content = null, Dictionary<string, string> headers = null, TimeSpan? timeout = null) where T : class
{
    return await HandleExceptions(async () =>
    {
        var request = CreateRequest(uri, method, content, headers, timeout);

        var policyWrap = Policy.WrapAsync(_policyRegistry.Get<IAsyncPolicy<HttpResponseMessage>>("RetryPolicy"),
                                          _policyRegistry.Get<IAsyncPolicy<HttpResponseMessage>>("CachePolicy"));

        var response = await policyWrap.ExecuteAsync(async () => await _client.SendAsync(request));

        var responseBody = await response.Content.ReadAsStringAsync();

        if (!response.IsSuccessStatusCode)
        {
            _logger.LogWarning($"Received HTTP {response.StatusCode} for {method} request to {uri}. Response body: {responseBody}");

            if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
            {
                // Handle 404 status code
                _logger.LogError($"The requested resource at {uri} was not found.");
            }

            throw new HttpRequestException($"Request to {uri} failed with status code {response.StatusCode}. Response body: {responseBody}");
        }

        // Handle responses according to their MIME type
        if (response.Content.Headers.ContentType.MediaType == "application/json")
        {
            return JsonConvert.DeserializeObject<T>(responseBody);
        }
        else if (response.Content.Headers.ContentType.MediaType == "text/plain")
        {
            return responseBody as T;
        }
        else
        {
            throw new NotSupportedException($"Unsupported content type: {response.Content.Headers.ContentType.MediaType}");
        }
    });
}

Bu yeni kod parçacığı, 404 Not Found durum kodunu ve “application/json” ve “text/plain” MIME türlerini özel olarak ele alır.



More posts like this

The SemaphoreSlim Class: Multitask-Based Programming in C#

2023-06-11 | #net #semaphoreslim

Overview The SemaphoreSlim class is a structure used in C# to control one or more threads using a specific resource or operation concurrently. SemaphoreSlim limits the number of threads that can access the resource at the same time. The use of SemaphoreSlim is often used to prevent deadlock situations in multi-threaded applications and to ensure that a specific resource is used by only one or more threads at the same time.

Continue reading 


LINQ and Optimistic Concurrency: Methods for Ensuring Data Integrity

2023-06-11 | #linq #net #optimistic-concurrency

When working with databases, it is of great importance to properly manage concurrent operations and ensure data integrity. Concurrency control is used to manage multiple users or processes accessing the same data concurrently. In this article, we will explore how to ensure data integrity using LINQ (Language Integrated Query) with optimistic concurrency. What is Optimistic Concurrency? Optimistic concurrency is a method where resources are not locked when a transaction begins, but changes are checked before the transaction is completed.

Continue reading 


LINQ and Pessimistic Concurrency: Methods for Ensuring Data Integrity

2023-06-11 | #linq #net #pessimistic-concurrency

When working with databases, managing concurrent operations and ensuring data integrity are of great importance. Concurrency control is used to manage multiple users or processes accessing the same data concurrently. In this article, we will explore how to use LINQ (Language Integrated Query) with pessimistic concurrency to maintain data integrity. What is Pessimistic Concurrency? Pessimistic concurrency is based on the principle of locking the relevant data when a transaction begins and maintaining the lock until the transaction is completed.

Continue reading 