zhaolei
2020-11-20 4a2e5b9a21940f11757be37d99f0944e240e908b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#if NETSTANDARD2_0
using Newtonsoft.Json;
#else
using Microsoft.Extensions.DependencyInjection;
using System.Text.Json;
#endif
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
 
namespace Bootstrap.Security
{
    internal class BootstrapAdminHttpClient
    {
        private readonly HttpClient _client;
 
        public BootstrapAdminHttpClient(HttpClient client) => _client = client;
 
#nullable disable
#if NETSTANDARD2_0
        public async Task<T> PostAsJsonAsync<T>(string requestUri, object postData)
#else
        public async Task<T> PostAsJsonAsync<T>(string requestUri, object postData, JsonSerializerOptions options = null)
#endif
        {
            var ret = default(T);
            try
            {
#if NETSTANDARD2_0
                var sc = new StringContent(JsonConvert.SerializeObject(postData));
#else
                if (options == null) options = new JsonSerializerOptions().AddDefaultConverters();
                var sc = new StringContent(JsonSerializer.Serialize(postData, options));
#endif
                sc.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                var result = await _client.PostAsync(requestUri, sc);
                if (result.IsSuccessStatusCode)
                {
                    var content = await result.Content.ReadAsStringAsync();
#if NETSTANDARD2_0
                    ret = JsonConvert.DeserializeObject<T>(content);
#else
                    ret = JsonSerializer.Deserialize<T>(content, options);
#endif
                }
            }
            catch { }
            return ret;
        }
#nullable restore
    }
}