Repository navigation
Expand file tree
/
Copy pathContentTypes.cs
More file actions
370 lines (303 loc) · 14.8 KB
/
Copy pathContentTypes.cs
File metadata and controls
370 lines (303 loc) · 14.8 KB
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using ServiceStack.Serialization;
using ServiceStack.Text;
using ServiceStack.Web;
namespace ServiceStack.Host
{
public class ContentTypes : IContentTypes
{
private static readonly UTF8Encoding UTF8EncodingWithoutBom = new UTF8Encoding(false);
public static ContentTypes Instance = new();
public Dictionary<string, StreamSerializerDelegate> ContentTypeSerializers = new() {
{ MimeTypes.Json, (r, o, s) => HostContext.AppHost.OnSerializeJson(r, o, s) },
{ MimeTypes.Jsv, (r, o, s) => TypeSerializer.SerializeToStream(o, s) },
{ MimeTypes.Xml, (r, o, s) => XmlSerializer.SerializeToStream(o, s) },
};
public Dictionary<string, StreamDeserializerDelegate> ContentTypeDeserializers = new() {
{ MimeTypes.Json, (t, s) => HostContext.AppHost.OnDeserializeJson(t,s) },
{ MimeTypes.Jsv, TypeSerializer.DeserializeFromStream },
{ MimeTypes.Xml, XmlSerializer.DeserializeFromStream },
{ "text/xml; charset=utf-8", XmlSerializer.DeserializeFromStream }, //"text/xml; charset=utf-8" matches xml + soap11
};
public Dictionary<string, StreamSerializerDelegateAsync> ContentTypeSerializersAsync = new();
public Dictionary<string, StreamDeserializerDelegateAsync> ContentTypeDeserializersAsync = new()
{
{ MimeTypes.Json, JsonSerializer.DeserializeFromStreamAsync },
{ MimeTypes.Jsv, TypeSerializer.DeserializeFromStreamAsync },
};
public readonly Dictionary<string, StringSerializerDelegate> ContentTypeStringSerializers = new() {
{ MimeTypes.Json, (r, o) => JsonDataContractSerializer.Instance.SerializeToString(o) },
{ MimeTypes.Jsv, (r, o) => TypeSerializer.SerializeToString(o) },
{ MimeTypes.Xml, (r, o) => XmlSerializer.SerializeToString(o) },
};
public readonly Dictionary<string, StringDeserializerDelegate> ContentTypeStringDeserializers = new() {
{ MimeTypes.Json, JsonDataContractSerializer.Instance.DeserializeFromString },
{ MimeTypes.Jsv, TypeSerializer.DeserializeFromString },
{ MimeTypes.Xml, XmlSerializer.DeserializeFromString },
};
public static StreamSerializerDelegateAsync UnknownContentTypeSerializer { get; set; } = SerializeUnknownContentType;
public static StreamDeserializerDelegateAsync UnknownContentTypeDeserializer { get; set; }
public static HashSet<string> KnownFormats = new() {
"json",
"xml",
"jsv",
"csv",
"html",
"protobuf",
"msgpack",
"wire",
};
//built-in formats
public Dictionary<string, string> ContentTypeFormats { get; } = new() {
{ "json", MimeTypes.Json },
{ "xml", MimeTypes.Xml },
{ "jsv", MimeTypes.Jsv },
};
public string GetFormatContentType(string format)
{
return ContentTypeFormats.TryGetValue(format, out var registeredFormat)
? registeredFormat
: format switch {
"json" => MimeTypes.Json,
"xml" => MimeTypes.Xml,
"jsv" => MimeTypes.Jsv,
"csv" => MimeTypes.Csv,
_ => null,
};
}
public void Register(string contentType, StreamSerializerDelegate streamSerializer, StreamDeserializerDelegate streamDeserializer)
{
if (contentType.IsNullOrEmpty())
throw new ArgumentNullException(nameof(contentType));
var format = ContentFormat.GetContentFormat(contentType);
var normalizedContentType = ContentFormat.NormalizeContentType(contentType);
ContentTypeFormats[format] = normalizedContentType;
if (streamSerializer != null)
SetContentTypeSerializer(normalizedContentType, streamSerializer);
if (streamDeserializer != null)
SetContentTypeDeserializer(normalizedContentType, streamDeserializer);
}
public void RegisterAsync(string contentType,
StreamSerializerDelegateAsync streamSerializer, StreamDeserializerDelegateAsync streamDeserializer)
{
if (contentType.IsNullOrEmpty())
throw new ArgumentNullException(nameof(contentType));
var format = ContentFormat.GetContentFormat(contentType);
var normalizedContentType = ContentFormat.NormalizeContentType(contentType);
ContentTypeFormats[format] = normalizedContentType;
if (streamSerializer != null)
ContentTypeSerializersAsync[normalizedContentType] = streamSerializer;
if (streamDeserializer != null)
ContentTypeDeserializersAsync[normalizedContentType] = streamDeserializer;
}
public void Remove(string contentType)
{
contentType = ContentFormat.NormalizeContentType(contentType);
ContentTypeFormats.Remove(contentType);
ContentTypeSerializers.Remove(contentType);
ContentTypeSerializersAsync.Remove(contentType);
ContentTypeStringSerializers.Remove(contentType);
ContentTypeDeserializers.Remove(contentType);
ContentTypeDeserializersAsync.Remove(contentType);
ContentTypeStringDeserializers.Remove(contentType);
if (contentType == MimeTypes.Xml)
{
//"text/xml; charset=utf-8" also matches xml
ContentTypeSerializers.Remove(MimeTypes.Soap11);
ContentTypeDeserializers.Remove(MimeTypes.Soap11);
}
}
public void SetContentTypeSerializer(string contentType, StreamSerializerDelegate streamSerializer)
{
ContentTypeSerializers[ContentFormat.NormalizeContentType(contentType)] = streamSerializer;
}
public void SetContentTypeDeserializer(string contentType, StreamDeserializerDelegate streamDeserializer)
{
ContentTypeDeserializers[ContentFormat.NormalizeContentType(contentType)] = streamDeserializer;
}
public static async Task SerializeUnknownContentType(IRequest req, object response, Stream stream)
{
req.Response.Dto = response;
if (stream == Stream.Null)
return;
switch (response)
{
case string text:
await stream.WriteAsync(text).ConfigAwait();
break;
case byte[] bytes:
await stream.WriteAsync(bytes, 0, bytes.Length).ConfigAwait();
break;
case MemoryStream input:
await input.WriteToAsync(stream);
break;
case Stream input:
await input.CopyToAsync(stream);
break;
case ErrorResponse errorDto: //ignore writing ErrorResponse bodies for unknown content types
break;
#if !NETCORE
case System.Drawing.Image img:
img.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
break;
#endif
default:
throw new NotSupportedException(ErrorMessages.ContentTypeNotSupportedFmt.LocalizeFmt(req, req.ResponseContentType));
}
}
public byte[] SerializeToBytes(IRequest req, object response)
{
var contentType = ContentFormat.NormalizeContentType(req.ResponseContentType);
var responseStreamWriter = GetStreamSerializer(contentType);
if (responseStreamWriter != null)
{
using (var ms = MemoryStreamFactory.GetStream())
{
responseStreamWriter(req, response, ms);
ms.Position = 0;
return ms.ToArray();
}
}
var responseWriterAsync = GetStreamSerializerAsync(contentType);
if (responseWriterAsync != null)
{
using (var ms = MemoryStreamFactory.GetStream())
{
responseWriterAsync(req, response, ms).Wait();
ms.Position = 0;
return ms.ToArray();
}
}
throw new NotSupportedException(ErrorMessages.ContentTypeNotSupportedFmt.LocalizeFmt(req, contentType));
}
public string SerializeToString(IRequest req, object response)
{
var contentType = ContentFormat.NormalizeContentType(req.ResponseContentType);
if (ContentTypeStringSerializers.TryGetValue(contentType, out var stringSerializer))
{
return stringSerializer(req, response);
}
var responseStreamWriter = GetStreamSerializer(contentType);
if (responseStreamWriter != null)
{
using (var ms = MemoryStreamFactory.GetStream())
{
responseStreamWriter(req, response, ms);
return ms.ReadToEnd();
}
}
var responseWriterAsync = GetStreamSerializerAsync(contentType);
if (responseWriterAsync != null)
{
using (var ms = MemoryStreamFactory.GetStream())
{
responseWriterAsync(req, response, ms).Wait();
return ms.ReadToEnd();
}
}
throw new NotSupportedException(ErrorMessages.ContentTypeNotSupportedFmt.LocalizeFmt(req, contentType));
}
private static Task serializeAsync(StreamSerializerDelegateAsync serializer, IRequest httpReq, object dto, Stream stream)
{
httpReq.Response.Dto = dto;
if (stream == Stream.Null)
return TypeConstants.EmptyTask;
return serializer(httpReq, dto, stream);
}
private static async Task serializeSync(StreamSerializerDelegate serializer, IRequest httpReq, object dto, Stream stream)
{
httpReq.Response.Dto = dto;
if (stream == Stream.Null)
return;
if (HostContext.Config.BufferSyncSerializers)
{
using (var ms = MemoryStreamFactory.GetStream())
{
serializer(httpReq, dto, ms);
ms.Position = 0;
await ms.CopyToAsync(stream);
return;
}
}
httpReq.Response.AllowSyncIO();
serializer(httpReq, dto, stream);
}
public Task SerializeToStreamAsync(IRequest req, object response, Stream responseStream)
{
var contentType = ContentFormat.NormalizeContentType(req.ResponseContentType);
var serializer = GetStreamSerializer(contentType);
if (serializer != null)
return serializeSync(serializer, req, response, responseStream);
var serializerAsync = GetStreamSerializerAsync(contentType);
if (serializerAsync != null)
return serializerAsync(req, response, responseStream);
throw new NotSupportedException(ErrorMessages.ContentTypeNotSupportedFmt.LocalizeFmt(req, contentType));
}
public StreamSerializerDelegateAsync GetStreamSerializerAsync(string contentType)
{
contentType = ContentFormat.NormalizeContentType(contentType);
if (ContentTypeSerializersAsync.TryGetValue(contentType, out var asyncSerializer))
return (httpReq, dto, stream) =>
serializeAsync(asyncSerializer, httpReq, dto, stream);
var serializer = GetStreamSerializer(contentType);
if (serializer == null)
return UnknownContentTypeSerializer;
return (httpReq, dto, stream) =>
serializeSync(serializer, httpReq, dto, stream);
}
public StreamSerializerDelegate GetStreamSerializer(string contentType)
{
return ContentTypeSerializers.TryGetValue(ContentFormat.NormalizeContentType(contentType), out var serializer)
? serializer
: null;
}
public object DeserializeFromString(string contentType, Type type, string request)
{
contentType = ContentFormat.NormalizeContentType(contentType);
if (ContentTypeStringDeserializers.TryGetValue(contentType, out var stringDeserializer))
return stringDeserializer(request, type);
var deserializerAsync = GetStreamDeserializerAsync(contentType);
if (deserializerAsync != null)
{
using var ms = MemoryStreamFactory.GetStream(request.ToUtf8Bytes());
var task = deserializerAsync(type, ms);
return task.Result;
}
throw new NotSupportedException(ErrorMessages.ContentTypeNotSupportedFmt.LocalizeFmt(contentType));
}
public object DeserializeFromStream(string contentType, Type type, Stream fromStream)
{
contentType = ContentFormat.NormalizeContentType(contentType);
var deserializer = GetStreamDeserializer(contentType);
if (deserializer != null)
return deserializer(type, fromStream);
var deserializerAsync = GetStreamDeserializerAsync(contentType);
if (deserializerAsync != null)
{
var task = deserializerAsync(type, fromStream);
return task.Result;
}
throw new NotSupportedException(ErrorMessages.ContentTypeNotSupportedFmt.LocalizeFmt(contentType));
}
public StreamDeserializerDelegate GetStreamDeserializer(string contentType)
{
return ContentTypeDeserializers.TryGetValue(ContentFormat.NormalizeContentType(contentType), out var deserializer)
? deserializer
: null;
}
public StreamDeserializerDelegateAsync GetStreamDeserializerAsync(string contentType)
{
contentType = ContentFormat.NormalizeContentType(contentType);
if (ContentTypeDeserializersAsync.TryGetValue(contentType, out var deserializerAsync))
return deserializerAsync;
var deserializer = GetStreamDeserializer(contentType);
if (deserializer == null)
return UnknownContentTypeDeserializer;
return (type, stream) => Task.FromResult(deserializer(type, stream));
}
}
}