// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using Microsoft.Teams.Common.Logging; namespace Microsoft.Teams.Common.Http; /// /// Http Client Options /// public interface IHttpClientOptions : IHttpRequestOptions { /// /// The client name /// public string? Name { get; set; } /// /// The authorization token to use /// public object? Token { get; set; } /// /// The authorization token factory to use /// public HttpTokenFactory? TokenFactory { get; set; } /// /// ILogger instance to use /// public ILogger? Logger { get; set; } /// /// Default request timeout (ms) /// public TimeSpan? Timeout { get; set; } /// /// apply options to an http client /// /// the client to apply the http options to public void Apply(System.Net.Http.HttpClient client); /// /// apply options to an http request /// /// the request to apply the http options to public void Apply(HttpRequestMessage request); /// /// a factory for adding a token to http requests /// public delegate object? HttpTokenFactory(); } /// /// Http Client Options /// public class HttpClientOptions : HttpRequestOptions, IHttpClientOptions { /// /// The client name /// public string? Name { get; set; } /// /// The authorization token to use /// public object? Token { get; set; } /// /// The authorization token factory to use /// public IHttpClientOptions.HttpTokenFactory? TokenFactory { get; set; } /// /// ILogger instance to use /// public ILogger? Logger { get; set; } /// /// Default request timeout (ms) /// public TimeSpan? Timeout { get; set; } /// /// apply options to an http client /// /// the client to apply the http options to public void Apply(System.Net.Http.HttpClient client) { if (Timeout is not null) client.Timeout = (TimeSpan)Timeout; if (Token is not null) client.DefaultRequestHeaders.Add("Authorization", $"Bearer {Token}"); foreach (var kv in Headers) { client.DefaultRequestHeaders.TryAddWithoutValidation(kv.Key, kv.Value); } } /// /// apply options to an http request /// /// the request to apply the http options to public void Apply(HttpRequestMessage request) { if (TokenFactory is not null) { var token = TokenFactory(); if (token is not null) { request.Headers.Authorization = new("Bearer", token.ToString()); } } foreach (var kv in Headers) { if (kv.Key.StartsWith("Content-")) { request.Content?.Headers.TryAddWithoutValidation(kv.Key, kv.Value); continue; } request.Headers.TryAddWithoutValidation(kv.Key, kv.Value); } } }