How to wrap HttpClient for validation in C #

I am calling an external API and want my API to be a module for testing. And for this I am trying to wrap an HttpClient. I need only one method. Here is my interface.

public interface IHttpClient
{
    Task<string> GetStringAsync(string url);
}

And this is how I implemented it.

public class HttpClientWrapper: IHttpClient {private readonly HttpClient _httpClient;

    public HttpClientWrapper()
    {
        // I could also inject this but I think this will be fine as is. 
        _httpClient = new HttpClient(new HttpClientHandler(), false);
    }

    public async Task<string> GetStringAsync(string url)
    {
        //validate url here
        return await _httpClient.GetStringAsync(url);
    }

}

I have doubts? is this the right way to do this? Will the bool parameter result in a resource leak here? I read a couple of conflicting ideas about whether the HttpClient should be configured on every call or not. I took the non-disposable side, but really not quite sure. If there is a way to use HttpClient without a wrapper, but make the API validate, that would be great too. But so far I have not succeeded.

Thanks CleanKoder

+4
1

, HttpClient ! HttpClient HttpMessageHandler. Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) , , , , .

, , :

public class FakeHttpMessageHandler : HttpMessageHandler
{
    public HttpRequestMessage LastRequest;
    public string LastRequestString = string.Empty;
    public string ResponseContent = string.Empty;
    public HttpStatusCode ResponseStatusCode = HttpStatusCode.OK;

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
        CancellationToken cancellationToken)
    {
        if (request.Content != null)
        {
            LastRequestString = await request.Content.ReadAsStringAsync();
        }
        LastRequest = request;
        return await Task.FromResult(new HttpResponseMessage
        {
            StatusCode = ResponseStatusCode,
            Content = new StringContent(ResponseContent)
        });
    }
}

, ​​ NSubstitute, .

+1

Source: https://habr.com/ru/post/1547673/


All Articles