forked from reactiveui/refit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
XmlContentSerializer.cs
191 lines (166 loc) · 7.02 KB
/
XmlContentSerializer.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;
namespace Refit
{
/// <summary>
/// A <see langword="class"/> implementing <see cref="IHttpContentSerializer"/> which provides Xml content serialization.
/// </summary>
public class XmlContentSerializer : IHttpContentSerializer
{
readonly XmlContentSerializerSettings settings;
readonly ConcurrentDictionary<Type, XmlSerializer> serializerCache = new();
public XmlContentSerializer()
: this(new XmlContentSerializerSettings()) { }
public XmlContentSerializer(XmlContentSerializerSettings settings)
{
this.settings = settings ?? throw new ArgumentNullException(nameof(settings));
}
/// <summary>
/// Serialize object of type <typeparamref name="T"/> to a <see cref="HttpContent"/> with Xml.
/// </summary>
/// <typeparam name="T">Type of the object to serialize from.</typeparam>
/// <param name="item">Object to serialize.</param>
/// <returns><see cref="HttpContent"/> that contains the serialized <typeparamref name="T"/> object in Xml.</returns>
/// <exception cref="ArgumentNullException"></exception>
public HttpContent ToHttpContent<T>(T item)
{
if (item is null)
throw new ArgumentNullException(nameof(item));
var xmlSerializer = serializerCache.GetOrAdd(
item.GetType(),
t => new XmlSerializer(t, settings.XmlAttributeOverrides)
);
using var stream = new MemoryStream();
using var writer = XmlWriter.Create(
stream,
settings.XmlReaderWriterSettings.WriterSettings
);
var encoding =
settings.XmlReaderWriterSettings.WriterSettings?.Encoding ?? Encoding.Unicode;
xmlSerializer.Serialize(writer, item, settings.XmlNamespaces);
var str = encoding.GetString(stream.ToArray());
var content = new StringContent(str, encoding, "application/xml");
return content;
}
/// <summary>
/// Deserializes an object of type <typeparamref name="T"/> from a <see cref="HttpContent"/> object that contains Xml content.
/// </summary>
/// <typeparam name="T">Type of the object to deserialize to.</typeparam>
/// <param name="content">HttpContent object with Xml content to deserialize.</param>
/// <param name="cancellationToken">CancellationToken to abort the deserialization.</param>
/// <returns>The deserialized object of type <typeparamref name="T"/>.</returns>
public async Task<T?> FromHttpContentAsync<T>(
HttpContent content,
CancellationToken cancellationToken = default
)
{
var xmlSerializer = serializerCache.GetOrAdd(
typeof(T),
t =>
new XmlSerializer(
t,
settings.XmlAttributeOverrides,
Array.Empty<Type>(),
null,
settings.XmlDefaultNamespace
)
);
using var input = new StringReader(
await content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false)
);
using var reader = XmlReader.Create(
input,
settings.XmlReaderWriterSettings.ReaderSettings
);
return (T?)xmlSerializer.Deserialize(reader);
}
/// <inheritdoc/>
public string? GetFieldNameForProperty(PropertyInfo propertyInfo)
{
if (propertyInfo is null)
throw new ArgumentNullException(nameof(propertyInfo));
return propertyInfo
.GetCustomAttributes<XmlElementAttribute>(true)
.Select(a => a.ElementName)
.FirstOrDefault()
?? propertyInfo
.GetCustomAttributes<XmlAttributeAttribute>(true)
.Select(a => a.AttributeName)
.FirstOrDefault();
}
}
public class XmlReaderWriterSettings
{
XmlReaderSettings readerSettings;
XmlWriterSettings writerSettings;
public XmlReaderWriterSettings()
: this(new XmlReaderSettings(), new XmlWriterSettings()) { }
public XmlReaderWriterSettings(XmlReaderSettings readerSettings)
: this(readerSettings, new XmlWriterSettings()) { }
public XmlReaderWriterSettings(XmlWriterSettings writerSettings)
: this(new XmlReaderSettings(), writerSettings) { }
#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
public XmlReaderWriterSettings(
XmlReaderSettings readerSettings,
XmlWriterSettings writerSettings
)
#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
{
ReaderSettings = readerSettings;
WriterSettings = writerSettings;
}
public XmlReaderSettings ReaderSettings
{
get
{
ApplyOverrideSettings();
return readerSettings;
}
set => readerSettings = value ?? throw new ArgumentNullException(nameof(value));
}
public XmlWriterSettings WriterSettings
{
get
{
ApplyOverrideSettings();
return writerSettings;
}
set => writerSettings = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
/// The writer and reader settings are set by the caller, but certain properties
/// should remain set to meet the demands of the XmlContentSerializer. Those properties
/// are always set here.
/// </summary>
void ApplyOverrideSettings()
{
writerSettings.Async = true;
readerSettings.Async = true;
}
}
public class XmlContentSerializerSettings
{
public XmlContentSerializerSettings()
{
XmlDefaultNamespace = null;
XmlReaderWriterSettings = new XmlReaderWriterSettings();
XmlNamespaces = new XmlSerializerNamespaces(
new[] { new XmlQualifiedName(string.Empty, string.Empty), }
);
XmlAttributeOverrides = new XmlAttributeOverrides();
}
public string? XmlDefaultNamespace { get; set; }
public XmlReaderWriterSettings XmlReaderWriterSettings { get; set; }
public XmlSerializerNamespaces XmlNamespaces { get; set; }
public XmlAttributeOverrides XmlAttributeOverrides { get; set; }
}
}