Class HttpClientExtensions
- Namespace
- Codebelt.Extensions.Xunit.Hosting.AspNetCore
- Assembly
- Codebelt.Extensions.Xunit.Hosting.AspNetCore.dll
Provides extension methods for the HttpClient class.
public static class HttpClientExtensions
- Inheritance
-
HttpClientExtensions
Examples
The following example sends an HTTP request using the ToHttpResponseMessageAsync extension on an HttpClient. By default it performs a GET request to the root URL ("/"), or you can supply a custom response factory delegate. This method is designed to work with test host fixtures that provide a pre-configured HttpClient.
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Codebelt.Extensions.Xunit.Hosting.AspNetCore;
namespace WebFixtureTests;
public class HttpClientExample
{
public async Task DemonstrateAsync(HttpClient client)
{
var response = await client.ToHttpResponseMessageAsync().ConfigureAwait(false);
Console.WriteLine(response.StatusCode);
}
}
Methods
ToHttpResponseMessageAsync(HttpClient, Func<HttpClient, Task<HttpResponseMessage>>)
Provides a convenient way to return a HttpResponseMessage from a HttpClient using the specified responseFactory.
public static Task<HttpResponseMessage> ToHttpResponseMessageAsync(this HttpClient client, Func<HttpClient, Task<HttpResponseMessage>> responseFactory = null)
Parameters
clientHttpClientThe HttpClient to extend.
responseFactoryFunc<HttpClient, Task<HttpResponseMessage>>The function delegate that creates a HttpResponseMessage from the HttpClient. Default is a GET request to the root URL ("/").
Returns
- Task<HttpResponseMessage>
A Task that represents the asynchronous operation. The task result contains the HttpResponseMessage generated by the
responseFactory.
Remarks
Designed to be used in conjunction with RunAsync(Action<IServiceCollection>, Action<IApplicationBuilder>, Action<IHostBuilder>, Func<HttpClient, Task<HttpResponseMessage>>, IWebHostFixture) and RunWithHostBuilderContextAsync(Action<HostBuilderContext, IServiceCollection>, Action<HostBuilderContext, IApplicationBuilder>, Action<IHostBuilder>, Func<HttpClient, Task<HttpResponseMessage>>, IWebHostFixture).
Exceptions
- ArgumentNullException
clientcannot be null.