Skip to content

Commit 274a75f

Browse files
Krystal Culpkmjjc
authored andcommitted
persist restclient headers during build method
1 parent fcf7351 commit 274a75f

1 file changed

Lines changed: 23 additions & 7 deletions

File tree

src/VirtualClient/VirtualClient.Common/Rest/RestClientBuilder.cs

Lines changed: 23 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,10 @@ public class RestClientBuilder : IRestClientBuilder
1818
private TimeSpan? httpTimeout;
1919
private bool disposed = false;
2020

21+
private List<MediaTypeWithQualityHeaderValue> acceptedMediaTypes;
22+
private AuthenticationHeaderValue authenticationHeader;
23+
2124
#pragma warning disable CA2213 // We will reuse these single objects for the lifetime of virtual client execution
22-
private RestClient restClient;
2325
private HttpClientHandler handler;
2426
#pragma warning restore CA2213 // Disposable fields should be disposed
2527

@@ -29,23 +31,23 @@ public class RestClientBuilder : IRestClientBuilder
2931
/// <param name="timeout">The HTTP timeout to apply.</param>
3032
public RestClientBuilder(TimeSpan? timeout = null)
3133
{
32-
this.restClient = new RestClient();
3334
this.httpTimeout = timeout;
3435
this.handler = new HttpClientHandler();
36+
this.acceptedMediaTypes = new List<MediaTypeWithQualityHeaderValue>();
3537
}
3638

3739
/// <inheritdoc/>
3840
public IRestClientBuilder AddAuthorizationHeader(string authToken, string headerName = "Bearer")
3941
{
40-
this.restClient.SetAuthorizationHeader(new AuthenticationHeaderValue(headerName, authToken));
42+
this.authenticationHeader = new AuthenticationHeaderValue(authToken, headerName);
4143
return this;
4244
}
4345

4446
/// <inheritdoc/>
4547
public IRestClientBuilder AddAcceptedMediaType(MediaType mediaType)
4648
{
4749
mediaType.ThrowIfNull(nameof(mediaType));
48-
this.restClient.AddAcceptedMediaTypeHeader(new MediaTypeWithQualityHeaderValue(mediaType.FieldName));
50+
this.acceptedMediaTypes.Add(new MediaTypeWithQualityHeaderValue(mediaType.FieldName));
4951
return this;
5052
}
5153

@@ -74,13 +76,27 @@ public IRestClientBuilder AddCertificate(X509Certificate2 certificate)
7476
public IRestClient Build()
7577
{
7678
HttpClient client = new HttpClient(this.handler);
77-
this.restClient = new RestClient(client);
79+
RestClient restClient = new RestClient(client);
80+
81+
if (this.authenticationHeader != null)
82+
{
83+
restClient.SetAuthorizationHeader(this.authenticationHeader);
84+
}
85+
86+
if (this.acceptedMediaTypes.Count > 0)
87+
{
88+
foreach (var mediaType in this.acceptedMediaTypes)
89+
{
90+
restClient.AddAcceptedMediaTypeHeader(mediaType);
91+
}
92+
}
93+
7894
if (this.httpTimeout != null)
7995
{
80-
this.restClient.Client.Timeout = this.httpTimeout.Value;
96+
restClient.Client.Timeout = this.httpTimeout.Value;
8197
}
8298

83-
return this.restClient;
99+
return restClient;
84100
}
85101

86102
/// <inheritdoc/>

0 commit comments

Comments
 (0)