How to invoke a NSwag client method that needs bearer token on request header?

@oguzhan-soykan and @peter answers are both good - Here's an expansion of @peter's answer to show how you can implement a base class and not repeat yourself for every API client.

Requirements

  • NSwag.MSBuild package
  • Swagger .JSON definition

Create a base 'Client' class that exposes the functionality you need. Likely a bearer token property.

public abstract class MySwaggerClientBase
{
    public string BearerToken { get; private set; }

    public void SetBearerToken(string token)
    {
        BearerToken = token;
    }

    // Called by implementing swagger client classes
    protected Task<HttpRequestMessage> CreateHttpRequestMessageAsync(CancellationToken cancellationToken)
    {
        var msg = new HttpRequestMessage();
        // SET THE BEARER AUTH TOKEN
        msg.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", BearerToken);
        return Task.FromResult(msg);
    }

}

Edit your swagger code generation command to make use of the base class for all generated clients and use the UseHttpRequestMessageCreationMethod option.

<Project>
 ...
<Exec Command="$(NSwagExe) swagger2csclient /input:path-to-swagger-definition.json /output:$(ProjectDir)\Swagger.generated.cs /Namespace:MyNameSpace /ClientBaseClass:MySwaggerClientBase /UseHttpRequestMessageCreationMethod:true" />
 ...
</Project>

For the c# client you can specifcy UseHttpClientCreationMethodor UseHttpRequestMessageCreationMethod

(Cf. https://github.com/RicoSuter/NSwag/blob/master/src/NSwag.CodeGeneration.CSharp/SwaggerToCSharpClientGeneratorSettings.cs)

That way NSwag expects you to implement the methods for Creating A HttpClient or HttpRequest. You can set your headers there without any magic


I've resolved the issue by partial method. My example is:

CampaignClient.cs

public partial class CampaignClient
{
    partial void PrepareRequest(HttpClient request, ref string url);

    partial void ProcessResponse(HttpClient request, HttpResponseMessage response);

    //some codes...
}

CampaignClient.Extensions.cs - partial class:

public partial class CampaignClient
{
    private readonly IRequestContext _requestContext;
    private readonly IStartupConfiguration _startupConfiguration;

    public CampaignClient(IRequestContext requestContext, IStartupConfiguration startupConfiguration)
    {
        _requestContext = requestContext;
        _startupConfiguration = startupConfiguration;
    }

    partial void PrepareRequest(HttpClient request, ref string url)
    {
        request.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _requestContext.GetBearerTokenOrTriggerUnauthException());
    }
}

Method override has saved me!