0

We are using NSwag generated client code for a web API. The API requires an Authorization header to be set on all requests.

This header value needs to be generated from async library methods (ITokenAcquisition.GetAccessTokenForUserAsync() in case it matters).

So far the best option we've come up with is to create a class that implements

public Task<HttpResponseMessage> SendAsync(
  HttpRequestMessage request,
  HttpCompletionOption completionOption,
  CancellationToken cancellationToken)

wrapping an HTTPClient, which would allow us to get the token and set the header before calling SendAsync on the wrapped HttpClient. We can then inject that class as the HttpClient used by the NSwag code.

I don't think we can use NSwag's CreateHttpClientAsync because I can't see how to inject the ITokenAcquisition (and other dependencies) into the base class. (Unless the client generation code is cleverer than I'm giving it credit for)

Have we missed something?

Dan
  • 7,446
  • 6
  • 32
  • 46

1 Answers1

1

The best solution we came up with doesn't actually use any NSwag customisation in the end.

Instead we added a class inheriting from DelegatingHandler and overrode SendAsync there.

We then added our DelegatingHandler to the HttpClient passed to the NSwag client. e.g. during service registration:

    services.AddHttpClient<NSwagClientInterface, NSwagClientImplementation>((provider, client) =>
        {
            client.BaseAddress = new Uri(Configuration["BaseAddress"]);
        })
        .AddHttpMessageHandler<MyDelegatingHandler>();
Dan
  • 7,446
  • 6
  • 32
  • 46