forked from radzenhq/radzen-blazor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHttpResponseMessageExtensions.cs
98 lines (94 loc) · 3.68 KB
/
HttpResponseMessageExtensions.cs
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
using System;
using System.Linq;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace Radzen
{
/// <summary>
/// Class HttpResponseMessageExtensions.
/// </summary>
public static class HttpResponseMessageExtensions
{
/// <summary>
/// Read as an asynchronous operation.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="response">The response.</param>
/// <returns>A Task<T> representing the asynchronous operation.</returns>
/// <exception cref="Exception">Unable to parse the response.</exception>
/// <exception cref="Exception"></exception>
/// <exception cref="Exception">Unable to parse the response.</exception>
/// <exception cref="Exception"></exception>
public static async Task<T> ReadAsync<T>(this HttpResponseMessage response)
{
try
{
response.EnsureSuccessStatusCode();
using (var stream = await response.Content.ReadAsStreamAsync())
{
return stream.Length > 0 ? await JsonSerializer.DeserializeAsync<T>(stream, new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
PropertyNameCaseInsensitive = true,
}) : default(T);
}
}
catch
{
var responseAsString = await response.Content.ReadAsStringAsync();
if (!string.IsNullOrEmpty(responseAsString))
{
if (response.Content.Headers.ContentType.MediaType == "application/json")
{
JsonDocument json;
try
{
json = JsonDocument.Parse(responseAsString);
}
catch
{
throw new Exception("Unable to parse the response.");
}
JsonElement error;
if (json.RootElement.TryGetProperty("error", out error))
{
JsonElement message;
if (error.TryGetProperty("message", out message))
{
throw new Exception(message.GetString());
}
}
}
else
{
XElement error = null;
try
{
var xml = XDocument.Parse(responseAsString);
var innerException = xml.Descendants().SingleOrDefault(p => p.Name.LocalName == "internalexception");
if (innerException != null)
{
error = innerException;
}
else
{
error = xml.Descendants().SingleOrDefault(p => p.Name.LocalName == "error");
}
}
catch
{
throw new Exception("Unable to parse the response.");
}
if (error != null)
{
throw new Exception(error.Value);
}
}
}
throw;
}
}
}
}