0

Is it possible to add custom request headers using the NSwag CSharpClientGenerator?

I have this method generated from one of my API endpoints that takes in some parameters including a bearerToken. Notice in my HttpRequestMessageBody I have this hard coded not auto generated line // request_.Headers.Add("authorization", "Bearer " + bearerToken); how can I add this?. Is there some way to programmatically add this when generating my client API using a Swagger JSON payload?

public async System.Threading.Tasks.Task<UnifiedActivityMappingGroupMetadata> GetActivityMappingAsync(System.Guid instanceId, System.Guid groupId, string bearerToken, System.Threading.CancellationToken cancellationToken)
{
    if (instanceId == null)
        throw new System.ArgumentNullException("instanceId");

    if (groupId == null)
        throw new System.ArgumentNullException("groupId");

    if (bearerToken == null)
        throw new System.ArgumentNullException("bearerToken");

    var urlBuilder_ = new System.Text.StringBuilder();
    urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/instances/{instanceId}/manage/activitymappings/{groupId}");
    urlBuilder_.Replace("{instanceId}", System.Uri.EscapeDataString(ConvertToString(instanceId, System.Globalization.CultureInfo.InvariantCulture)));
    urlBuilder_.Replace("{groupId}", System.Uri.EscapeDataString(ConvertToString(groupId, System.Globalization.CultureInfo.InvariantCulture)));
    urlBuilder_.Replace("{bearerToken}", System.Uri.EscapeDataString(ConvertToString(bearerToken, System.Globalization.CultureInfo.InvariantCulture)));

    var client_ = _httpClient;
    try
    {
        using (var request_ = new System.Net.Http.HttpRequestMessage())
        {
            request_.Method = new System.Net.Http.HttpMethod("GET");
            // request_.Headers.Add("authorization", "Bearer " + bearerToken); how can I add this?
            request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json"));

            PrepareRequest(client_, request_, urlBuilder_);
            var url_ = urlBuilder_.ToString();
            request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
            PrepareRequest(client_, request_, url_);
greg
  • 1,118
  • 1
  • 20
  • 40
  • Got same question about TypeScript client generation. Docs are a bit poor (lack of examples for this case) a github threads seems to be outdated... – IT Man Mar 23 '20 at 15:32

1 Answers1

0

A solution can ba that you wrap the generated client with a custom class that

  • hides the unneeded client methods
  • returns internal types (does the mapping)
  • implements custom logic like the one you asked
Adel Tabareh
  • 1,478
  • 14
  • 10