{% template Client.Class.Annotations %}
[System.CodeDom.Compiler.GeneratedCode("NSwag", "{{ ToolchainVersion }}")]
{{ ClientClassAccessModifier }} partial class {{ Class }} {% if HasBaseType %}: {% endif %}{% if HasBaseClass %}{{ BaseClass }}{% if GenerateClientInterfaces %}, {% endif %}{% endif %}{% if GenerateClientInterfaces %}I{{ Class }}{% endif %}
{
{% if UseBaseUrl -%}
    #pragma warning disable 8618
    private string _baseUrl;
    #pragma warning restore 8618

{% endif -%}
{% if InjectHttpClient -%}
    private {{ HttpClientType }} _httpClient;
{% endif -%}
{% if UseRequestAndResponseSerializationSettings -%}
    private static System.Lazy<{{ JsonSerializerSettingsType }}> _requestSettings = new System.Lazy<{{ JsonSerializerSettingsType }}>(() => CreateSerializerSettings(true), true);
    private {{ JsonSerializerSettingsType }} _instanceRequestSettings;
    private static System.Lazy<{{ JsonSerializerSettingsType }}> _responseSettings = new System.Lazy<{{ JsonSerializerSettingsType }}>(() => CreateSerializerSettings(false), true);
    private {{ JsonSerializerSettingsType }} _instanceResponseSettings;
{% else -%}
    private static System.Lazy<{{ JsonSerializerSettingsType }}> _settings = new System.Lazy<{{ JsonSerializerSettingsType }}>(CreateSerializerSettings, true);
    private {{ JsonSerializerSettingsType }} _instanceSettings;
{% endif -%}

{% assign constructorParameters = "" -%}
{% if HasConfigurationClass -%}
{%     assign constructorParameters = ConfigurationClass | append: " configuration" -%}
{% endif -%}
{% if UseBaseUrl and HasBaseUrl == false and HasConfigurationClass == false -%}
{%     unless constructorParameters == "" -%}{% assign constructorParameters = constructorParameters | append: ", " -%}{% endunless -%}
{%     assign constructorParameters = constructorParameters | append: "string baseUrl" -%}
{% endif -%}
{% if InjectHttpClient -%}
{%     unless constructorParameters == "" -%}{% assign constructorParameters = constructorParameters | append: ", " -%}{% endunless -%}
{%     assign constructorParameters = constructorParameters | append: HttpClientType | append: " httpClient" -%}
{% endif -%}
#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
    public {{ Class }}({{ constructorParameters }}){% if HasConfigurationClass and HasBaseClass -%}{{ " : base(configuration)"}}{% endif %}
#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
    {
{%     if UseBaseUrl -%}
{%         if HasBaseUrl -%}
{%             if GenerateBaseUrlProperty -%}
        BaseUrl = "{{ BaseUrl }}";
{%             else -%}
{%                 if BaseUrl != "" -%}
{%                     assign baseUrlLength = BaseUrl | size -%}
{%                     assign lastUrlCharIndex = baseUrlLength | minus: 1 -%}
{%                     assign lastUrlChar = BaseUrl | slice: lastUrlCharIndex, 1 -%}
{%                     if lastUrlChar == "/" -%}
        _baseUrl = "{{ BaseUrl }}";
{%                     else -%}
        _baseUrl = "{{ BaseUrl }}/";
{%                     endif -%}
{%                 endif -%}
{%             endif -%}
{%         else -%}
{%             if GenerateBaseUrlProperty -%}
        BaseUrl = baseUrl;
{%             else -%}
{%                 if HasConfigurationClass == false -%}
        _baseUrl = (string.IsNullOrEmpty(baseUrl) || baseUrl.EndsWith("/"))
            ? baseUrl
            : baseUrl + "/";
{%                 endif -%}
{%             endif -%}
{%         endif -%}
{%     endif -%}
{%     if InjectHttpClient -%}
        _httpClient = httpClient;
{%     endif -%}
        Initialize();
    {% template Client.Class.Constructor %}
    }

    private static {{ JsonSerializerSettingsType }} CreateSerializerSettings({% if UseRequestAndResponseSerializationSettings %}bool isRequest{% endif %})
    {
        var settings = {{ JsonSerializerParameterCode }};
{% if UseSystemTextJson == false and SerializeTypeInformation -%}
        settings.TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Auto;
{% endif -%}
{% if UseSystemTextJson == true and JsonConvertersArrayCode contains "System.Text.Json.Serialization.JsonConverter[]" -%}
        var converters = {{ JsonConvertersArrayCode }};
        foreach(var converter in converters)
            settings.Converters.Add(converter);
{% endif -%}
        UpdateJsonSerializerSettings(settings{% if UseRequestAndResponseSerializationSettings %}, isRequest{% endif %});
        return settings;
    }

{% if UseBaseUrl and GenerateBaseUrlProperty -%}
    public string BaseUrl
    {
        get { return _baseUrl; }
        set
        {
            _baseUrl = value;
            if (!string.IsNullOrEmpty(_baseUrl) && !_baseUrl.EndsWith("/"))
                _baseUrl += '/';
        }
    }

{% endif -%}
{% if ExposeJsonSerializerSettings -%}
{%     assign serializerSettingsAccessModifier = "public" %}
{% else -%}
{%     assign serializerSettingsAccessModifier = "protected" %}
{% endif -%}
{% if UseRequestAndResponseSerializationSettings -%}
    {{ serializerSettingsAccessModifier }} {{ JsonSerializerSettingsType }} RequestJsonSerializerSettings { get { return _instanceRequestSettings ?? _requestSettings.Value; } }
    {{ serializerSettingsAccessModifier }} {{ JsonSerializerSettingsType }} ResponseJsonSerializerSettings { get { return _instanceResponseSettings ?? _responseSettings.Value; } }
{% else -%}
    {{ serializerSettingsAccessModifier }} {{ JsonSerializerSettingsType }} JsonSerializerSettings { get { return _instanceSettings ?? _settings.Value; } }
{% endif -%}

{% if GenerateUpdateJsonSerializerSettingsMethod -%}
{%     if UseRequestAndResponseSerializationSettings -%}
    static partial void UpdateJsonSerializerSettings({{ JsonSerializerSettingsType }} settings, bool isRequest);
{%     else -%}
    static partial void UpdateJsonSerializerSettings({{ JsonSerializerSettingsType }} settings);
{%     endif -%}
{% endif -%}

    partial void Initialize();

{% if GeneratePrepareRequestAndProcessResponseAsAsyncMethods == false -%}
    partial void PrepareRequest({{ HttpClientType }} client, System.Net.Http.HttpRequestMessage request, string url);
    partial void PrepareRequest({{ HttpClientType }} client, System.Net.Http.HttpRequestMessage request, System.Text.StringBuilder urlBuilder);
    partial void ProcessResponse({{ HttpClientType }} client, System.Net.Http.HttpResponseMessage response);
{% endif -%}
{% for operation in Operations %}
{%     if GenerateOptionalParameters == false -%}
    {% template Client.Method.Documentation %}
    {% template Client.Method.Annotations %}
    {{ operation.MethodAccessModifier }} virtual {{ operation.ResultType }} {{ operation.ActualOperationName }}Async({% for parameter in operation.Parameters %}{{ parameter.Type }} {{ parameter.VariableName }}{% if GenerateOptionalParameters and parameter.IsOptional %} = null{% endif %}{% if parameter.IsLast == false %}, {% endif %}{% endfor %})
    {
        return {{ operation.ActualOperationName }}Async({% for parameter in operation.Parameters %}{{ parameter.VariableName }}, {% endfor %}System.Threading.CancellationToken.None);
    }

{%     endif -%}
{%     if GenerateSyncMethods -%}
    {% template Client.Method.Documentation %}
    {% template Client.Method.Annotations %}
    {{ operation.MethodAccessModifier }} virtual {{ operation.SyncResultType }} {{ operation.ActualOperationName }}({% for parameter in operation.Parameters %}{{ parameter.Type }} {{ parameter.VariableName }}{% if GenerateOptionalParameters and parameter.IsOptional %} = null{% endif %}{% if parameter.IsLast == false %}, {% endif %}{% endfor %})
    {
        {% if operation.HasResult or operation.WrapResponse %}return {% endif %}System.Threading.Tasks.Task.Run(async () => await {{ operation.ActualOperationName }}Async({% for parameter in operation.Parameters %}{{ parameter.VariableName }}, {% endfor %}System.Threading.CancellationToken.None)).GetAwaiter().GetResult();
    }

{%     endif -%}
    /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
    {% template Client.Method.Documentation %}
    {% template Client.Method.Annotations %}
    {{ operation.MethodAccessModifier }} virtual async {{ operation.ResultType }} {{ operation.ActualOperationName }}Async({% for parameter in operation.Parameters %}{{ parameter.Type }} {{ parameter.VariableName }}{% if GenerateOptionalParameters and parameter.IsOptional %} = null{% endif %}, {% endfor %}System.Threading.CancellationToken cancellationToken{% if GenerateOptionalParameters %} = default(System.Threading.CancellationToken){% endif %})
    {
{%     for parameter in operation.PathParameters -%}
{%         if parameter.IsNullable == false and parameter.IsRequired -%}
        if ({{ parameter.VariableName }} == null)
            throw new System.ArgumentNullException("{{ parameter.VariableName }}");

{%         endif -%}
{%     endfor -%}
{%     for parameter in operation.QueryParameters -%}
{%         if parameter.IsNullable == false and parameter.IsRequired -%}
        if ({{ parameter.VariableName }} == null)
            throw new System.ArgumentNullException("{{ parameter.VariableName }}");

{%         endif -%}
{%     endfor -%}
{%     if operation.HasContent and operation.ContentParameter.IsRequired -%}
        if ({{ operation.ContentParameter.VariableName }} == null)
            throw new System.ArgumentNullException("{{ operation.ContentParameter.VariableName }}");

{%     endif -%}
{%     if InjectHttpClient -%}
        var client_ = _httpClient;
{%     elsif UseHttpClientCreationMethod -%}
        var client_ = await CreateHttpClientAsync(cancellationToken).ConfigureAwait(false);
{%     else -%}
        var client_ = new {{ HttpClientType }}();
{%     endif -%}
{%     if InjectHttpClient == false and DisposeHttpClient -%}
        var disposeClient_ = true;
{%     else -%}
        var disposeClient_ = false;
{%     endif -%}
        try
        {
{%     if UseHttpRequestMessageCreationMethod -%}
            using (var request_ = await CreateHttpRequestMessageAsync(cancellationToken).ConfigureAwait(false))
{%     else -%}
            using (var request_ = new System.Net.Http.HttpRequestMessage())
{%     endif -%}
            {
{%     for parameter in operation.HeaderParameters %}
{%         if parameter.IsRequired -%}
                if ({{ parameter.VariableName }} == null)
                    throw new System.ArgumentNullException("{{ parameter.VariableName }}");
                {% template Client.Class.HeaderParameter %}
{%         else -%}
                if ({{ parameter.VariableName }} != null)
                    {% template Client.Class.HeaderParameter %}
{%         endif -%}
{%     endfor -%}
{%     if operation.HasContent -%}
{%         if operation.HasBinaryBodyParameter -%}
{%             if operation.ContentParameter.HasBinaryBodyWithMultipleMimeTypes -%}
                var content_ = new System.Net.Http.StreamContent({{ operation.ContentParameter.VariableName }}.Data);
                content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse({{ operation.ContentParameter.VariableName }}.ContentType);
{%             else -%}
                var content_ = new System.Net.Http.StreamContent({{ operation.ContentParameter.VariableName }});
                content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("{{ operation.Consumes }}");
{%             endif -%}
{%         elsif operation.HasXmlBodyParameter -%}
                var content_ = new System.Net.Http.StringContent({{ operation.ContentParameter.VariableName }});
                content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("{{ operation.Consumes }}");
{%         elsif operation.ConsumesOnlyFormUrlEncoded -%}
                var json_ = {% if UseSystemTextJson %}System.Text.Json.JsonSerializer.SerializeToUtf8Bytes{% else %}Newtonsoft.Json.JsonConvert.SerializeObject{% endif %}({{ operation.ContentParameter.VariableName }}, JsonSerializerSettings);
                var dictionary_ = {% if UseSystemTextJson %}System.Text.Json.JsonSerializer.Deserialize{% else %}Newtonsoft.Json.JsonConvert.DeserializeObject{% endif %}<System.Collections.Generic.Dictionary<string, string>>(json_, JsonSerializerSettings);
                var content_ = new System.Net.Http.FormUrlEncodedContent(dictionary_);
                content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("{{ operation.Consumes }}");
{%         elsif operation.HasPlainTextBodyParameter -%}
                var content_ = new System.Net.Http.StringContent({{ operation.ContentParameter.VariableName }});
                content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("{{ operation.Consumes }}");
{%         else -%}
                var json_ = {% if UseSystemTextJson %}System.Text.Json.JsonSerializer.SerializeToUtf8Bytes{% else %}Newtonsoft.Json.JsonConvert.SerializeObject{% endif %}({{ operation.ContentParameter.VariableName }}, {% if SerializeTypeInformation %}typeof({{ operation.ContentParameter.Type }}), {% endif %}{% if UseRequestAndResponseSerializationSettings %}Request{% endif %}JsonSerializerSettings);
                var content_ = new System.Net.Http.{% if UseSystemTextJson %}ByteArrayContent{% else %}StringContent{% endif %}(json_);
                content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("{{ operation.Consumes }}");
{%         endif -%}
                request_.Content = content_;
{%     else -%}
{%         if operation.HasFormParameters -%}
{%             if operation.ConsumesOnlyFormUrlEncoded -%}
                var keyValues_ = new System.Collections.Generic.List<System.Collections.Generic.KeyValuePair<string, string>>();
{%                 for parameter in operation.FormParameters -%}
{%                     if parameter.IsNullable -%}
                if ({{ parameter.VariableName }} != null)
{%                     else -%}
                if ({{ parameter.VariableName }} == null)
                    throw new System.ArgumentNullException("{{ parameter.VariableName }}");
                else
{%                     endif -%}
                    keyValues_.Add(new System.Collections.Generic.KeyValuePair<string, string>("{{ parameter.Name }}", ConvertToString({{ parameter.VariableName }}, System.Globalization.CultureInfo.InvariantCulture)));
{%                 endfor -%}
                request_.Content = new System.Net.Http.FormUrlEncodedContent(keyValues_);
{%             else -%}
                var boundary_ = System.Guid.NewGuid().ToString();
                var content_ = new System.Net.Http.MultipartFormDataContent(boundary_);
                content_.Headers.Remove("Content-Type");
                content_.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + boundary_);
{%                 for parameter in operation.FormParameters %}
{%                     if parameter.IsNullable -%}
                if ({{ parameter.VariableName }} != null)
{%                     else -%}
                if ({{ parameter.VariableName }} == null)
                    throw new System.ArgumentNullException("{{ parameter.VariableName }}");
                else
{%                     endif -%}
                {
{%                     if parameter.IsFile -%}
{%                         if parameter.IsArray -%}
                    foreach (var item_ in {{ parameter.VariableName }})
                    {
                        var content_{{ parameter.VariableName }}_ = new System.Net.Http.StreamContent(item_.Data);
                        if (!string.IsNullOrEmpty(item_.ContentType))
                            content_{{ parameter.VariableName }}_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse(item_.ContentType);
                        content_.Add(content_{{ parameter.VariableName }}_, "{{ parameter.Name }}", item_.FileName ?? "{{ parameter.Name }}");
                    }
{%                         else -%}
                    var content_{{ parameter.VariableName }}_ = new System.Net.Http.StreamContent({{ parameter.VariableName }}.Data);
                    if (!string.IsNullOrEmpty({{ parameter.VariableName }}.ContentType))
                        content_{{ parameter.VariableName }}_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse({{ parameter.VariableName }}.ContentType);
                    content_.Add(content_{{ parameter.VariableName }}_, "{{ parameter.Name }}", {{ parameter.VariableName }}.FileName ?? "{{ parameter.Name }}");
{%                         endif -%}
{%                     elsif parameter.IsArray -%}
                    foreach (var item_ in {{ parameter.VariableName }})
                    {
                        content_.Add(new System.Net.Http.StringContent(ConvertToString(item_, System.Globalization.CultureInfo.InvariantCulture)), "{{ parameter.Name }}");
                    }
{%                     elsif parameter.IsObject -%}
                    var json_ = {% if UseSystemTextJson %}System.Text.Json.JsonSerializer.SerializeToUtf8Bytes{% else %}Newtonsoft.Json.JsonConvert.SerializeObject{% endif %}({{ parameter.VariableName }}, {% if UseRequestAndResponseSerializationSettings %}Request{% endif %}JsonSerializerSettings);
                    content_.Add(new System.Net.Http.{% if UseSystemTextJson %}ByteArrayContent(json_{% else %}StringContent(json_, System.Text.Encoding.UTF8, "application/json"{% endif %}), "{{ parameter.Name }}");
{%                     else -%}
                    content_.Add(new System.Net.Http.StringContent(ConvertToString({{ parameter.VariableName }}, System.Globalization.CultureInfo.InvariantCulture)), "{{ parameter.Name }}");
{%                     endif -%}
                }
{%                 endfor -%}
                request_.Content = content_;
{%             endif -%}
{%         elsif operation.IsGetOrDeleteOrHead == false -%}
                request_.Content = new System.Net.Http.StringContent(string.Empty, System.Text.Encoding.UTF8, "{{ operation.Consumes }}");
{%         endif -%}
{%     endif -%}
                request_.Method = new System.Net.Http.HttpMethod("{{ operation.HttpMethodUpper | upcase }}");
{%     if operation.HasResultType and operation.HasAcceptHeaderParameterParameter == false -%}
                request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("{{ operation.Produces }}"));
{%     endif -%}

                var urlBuilder_ = new System.Text.StringBuilder();
                {% if UseBaseUrl %}if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl);{% endif %}
                // Operation Path: "{{ operation.Path }}"
{%     if operation.Path contains "{" -%}
{%        assign pathParts = operation.Path | split: "{" -%}
{%        for pathPart in pathParts -%}
{%            if pathPart contains "}" -%}
{%                assign pathParameterParts = pathPart | split: "}" -%}
{%                assign pathParameterFound = true -%}
{%                for parameter in operation.PathParameters -%}
{%                    if parameter.Name == pathParameterParts[0] -%}
{%                        if parameter.IsOptional -%}
{%                            assign pathParameterFound = false -%}
                if ({{ parameter.VariableName }} != null)
                {
                    {% template Client.Class.PathParameter %}
                }
                else
                    if (urlBuilder_.Length > 0) urlBuilder_.Length--;
{%                        else -%}
                {% template Client.Class.PathParameter %}
{%                        endif -%}
{%                    endif -%}
{%                endfor -%}
{%                comment -%} >>> just in case {% endcomment -%}
{%                unless pathParameterFound -%}
                urlBuilder_.Append("{{ '{' }}{{ pathParameterParts[0] }}{{ '}' }}");
{%                endunless -%}
{%                comment -%} <<< just in case {% endcomment -%}
{%                assign nonParameterPartLengh = pathParameterParts[1] | size -%}
{%                if nonParameterPartLengh == 1 -%}
                urlBuilder_.Append('{{ pathParameterParts[1] }}');
{%                elsif nonParameterPartLengh > 0 -%}
                urlBuilder_.Append("{{ pathParameterParts[1] }}");
{%                endif -%}
{%            else -%}
{%                 unless pathPart == "" -%}
                urlBuilder_.Append("{{ pathPart }}");
{%                 endunless -%}
{%            endif -%}
{%        endfor -%}
{%    else -%}
{%        unless operation.Path == "" -%}
                urlBuilder_.Append("{{ operation.Path }}");
{%        endunless -%}
{%    endif -%}
{%     if operation.HasQueryParameters -%}
                urlBuilder_.Append('?');
{%         for parameter in operation.QueryParameters -%}
{%             if parameter.IsOptional -%}
                if ({{ parameter.VariableName }} != null)
                {
                    {% template Client.Class.QueryParameter %}
                }
{%             else -%}
                {% template Client.Class.QueryParameter %}
{%             endif -%}
{%         endfor -%}
                urlBuilder_.Length--;
{%     endif -%}

{% if GeneratePrepareRequestAndProcessResponseAsAsyncMethods %}
                await PrepareRequestAsync(client_, request_, urlBuilder_, cancellationToken).ConfigureAwait(false);
{% else -%}
                PrepareRequest(client_, request_, urlBuilder_);
{% endif -%}

                var url_ = urlBuilder_.ToString();
                request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);

{% if GeneratePrepareRequestAndProcessResponseAsAsyncMethods -%}
                await PrepareRequestAsync(client_, request_, url_, cancellationToken).ConfigureAwait(false);
{% else -%}
                PrepareRequest(client_, request_, url_);
{% endif -%}
                {% template Client.Class.BeforeSend %}

                var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
                var disposeResponse_ = true;
                try
                {
                    var headers_ = new System.Collections.Generic.Dictionary<string, System.Collections.Generic.IEnumerable<string>>();
                    foreach (var item_ in response_.Headers)
                        headers_[item_.Key] = item_.Value;
                    if (response_.Content != null && response_.Content.Headers != null)
                    {
                        foreach (var item_ in response_.Content.Headers)
                            headers_[item_.Key] = item_.Value;
                    }

{% if GeneratePrepareRequestAndProcessResponseAsAsyncMethods %}
                    await ProcessResponseAsync(client_, response_, cancellationToken).ConfigureAwait(false);
{% else %}
                    ProcessResponse(client_, response_);
{% endif %}

                    var status_ = (int)response_.StatusCode;
{%     for response in operation.Responses -%}
                    if (status_ == {{ response.StatusCode }}{% if response.CheckChunkedStatusCode %} || status_ == 206{% endif %})
                    {
                        {% template Client.Class.ProcessResponse %}
                    }
                    else
{%     endfor -%}
{%     if operation.HasDefaultResponse -%}
{%         if operation.DefaultResponse.HasType -%}
                    {
{%             assign response = operation.DefaultResponse -%}
                        {% template Client.Class.ProcessResponse %}
                    }
{%         elsif operation.HasSuccessResponse -%}
                    {
                        var responseData_ = response_.Content == null ? null : await ReadAsStringAsync(response_.Content, cancellationToken).ConfigureAwait(false);
                        throw new {{ ExceptionClass }}("{{ operation.DefaultResponse.ExceptionDescription }}", status_, responseData_, headers_, null);
                    }
{%        elsif operation.HasResultType -%}
{%             if operation.WrapResponse and operation.UnwrappedResultType != "FileResponse" %}
                    return new {{ ResponseClass }}<{{ operation.UnwrappedResultType }}>(status_, headers_, {{ operation.UnwrappedResultDefaultValue }});
{%             else -%}
                    {% if operation.HasResult %}return {{ operation.UnwrappedResultDefaultValue }};{% else %}return;{% endif %}
{%             endif -%}
{%         elsif operation.WrapResponse -%}
                    return new {{ ResponseClass }}(status_, headers_);
{%         endif -%}
{%     else -%}
{%         if operation.HasSuccessResponse == false -%}
{% comment -%}
    If the success response has already been explicitely declared, there is no need for this default code (because handled above).
    Otherwise, return default values on success because we don't want to throw on "unknown status code".
    Success is always expected
{%- endcomment %}
                    if (status_ == 200 || status_ == 204)
                    {
{%             if operation.HasResultType -%}
{%                 if operation.WrapResponse and operation.UnwrappedResultType != "FileResponse" %}
                        return new {{ ResponseClass }}<{{ operation.UnwrappedResultType }}>(status_, headers_, {{ operation.UnwrappedResultDefaultValue }});
{%                 else -%}
                        {% if operation.HasResult %}return {{ operation.UnwrappedResultDefaultValue }};{% else %}return;{% endif %}
{%                 endif -%}
{%             elsif operation.WrapResponse -%}
                        return new {{ ResponseClass }}(status_, headers_);
{%             else -%}{% comment %} This method isn't expected to return a value. Just return. {% endcomment %}
                        return;
{%             endif -%}
                    }
                    else
{%         endif -%}
                    {
                        var responseData_ = response_.Content == null ? null : await ReadAsStringAsync(response_.Content, cancellationToken).ConfigureAwait(false);
                        throw new {{ ExceptionClass }}("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null);
                    }
{%     endif -%}
                }
                finally
                {
                    if (disposeResponse_)
                        response_.Dispose();
                }
            }
        }
        finally
        {
            if (disposeClient_)
                client_.Dispose();
        }
    }

{% endfor %}
    protected struct ObjectResponseResult<T>
    {
        public ObjectResponseResult(T responseObject, string responseText)
        {
            this.Object = responseObject;
            this.Text = responseText;
        }

        public T Object { get; }

        public string Text { get; }
    }

    [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
    private static System.Threading.Tasks.Task<string> ReadAsStringAsync(System.Net.Http.HttpContent content, System.Threading.CancellationToken cancellationToken)
    {
#if NET5_0_OR_GREATER
        return content.ReadAsStringAsync(cancellationToken);
#else
        return content.ReadAsStringAsync();
#endif
    }

    [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
    private static System.Threading.Tasks.Task<System.IO.Stream> ReadAsStreamAsync(System.Net.Http.HttpContent content, System.Threading.CancellationToken cancellationToken)
    {
#if NET5_0_OR_GREATER
        return content.ReadAsStreamAsync(cancellationToken);
#else
        return content.ReadAsStreamAsync();
#endif
    }


    {% template Client.Class.ReadObjectResponse %}

    {% template Client.Class.ConvertToString %}
    {% template Client.Class.Body %}
}
