I want to test some of my local API's. I created a DelegatingHandler to set all the headers that are needed in my production code. but it doesn't work to have a DelegatingHandler for CreateClient in Moq Test to test local Api's.
this is my code:
var appFactory = new WebApplicationFactory<Program>();
Client = appFactory.CreateClient();
var cts = new CancellationTokenSource(100000);
var postData = new TestModel(){Name= "Test"};
var stringContent = new StringContent(JsonConvert.SerializeObject(postData), Encoding.UTF8, "application/json");
var response = await Client.PostAsync("/api/register", content, cts.Token);
this is MyDelegatingHandler:
public class MyDelegatingHandler: DelegatingHandler
{
private readonly IHttpContextAccessor _httpContextAccessor;
public MyDelegatingHandler(IHttpContextAccessor httpContextAccessor)
{
this._httpContextAccessor = httpContextAccessor;
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (_httpContextAccessor.HttpContext == null) return base.SendAsync(request, cancellationToken);
if (_httpContextAccessor.HttpContext.Request.Headers["Authorization"].Any())
{
var token = _httpContextAccessor.HttpContext.Request.Headers["Authorization"].FirstOrDefault();
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer",token);
}
return base.SendAsync(request, cancellationToken);
}
}
is there any way to set MyDelegatingHandler for Client to test local API's?