Repository navigation
Expand file tree
/
Copy pathContentTypeMiddleware.cs
More file actions
87 lines (74 loc) · 2.51 KB
/
Copy pathContentTypeMiddleware.cs
File metadata and controls
87 lines (74 loc) · 2.51 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
using Microsoft.AspNetCore.Http;
using SkPlayground.WebServer.Dtos;
using System.Text;
using System.Text.Json;
namespace SkPlayground.WebServer.Middleware;
public class ContentTypeMiddleware
{
private readonly RequestDelegate _next;
private readonly List<Type> _processableTypes;
public ContentTypeMiddleware(RequestDelegate next)
{
_next = next;
_processableTypes = new List<Type> { typeof(HashRequest), typeof(CertificateInfo) };
}
public async Task InvokeAsync(HttpContext context)
{
var buffer = new MemoryStream();
await context.Request.Body.CopyToAsync(buffer);
buffer.Position = 0;
using var reader = new StreamReader(buffer);
var content = await reader.ReadToEndAsync();
if (!string.IsNullOrEmpty(content) && TryDeserialize(content, out object deserializedObject))
{
ReplaceRequestBody(context, deserializedObject);
}
else
{
// Reset the buffer position for the next middleware
buffer.Position = 0;
context.Request.Body = buffer;
}
await _next(context);
}
private void ReplaceRequestBody(HttpContext context, object deserializedObject)
{
var newContent = JsonSerializer.Serialize(deserializedObject);
var newBody = new MemoryStream(Encoding.UTF8.GetBytes(newContent));
context.Request.Body = newBody;
context.Request.ContentType = "application/json";
}
private bool TryDeserialize(string content, out object deserializedObject)
{
foreach (var type in _processableTypes)
{
try
{
deserializedObject = JsonSerializer.Deserialize(content, type);
return true;
}
catch (JsonException)
{
// Continue to the next type
}
}
// Check if content is a JSON object or array
try
{
using var doc = JsonDocument.Parse(content);
if (doc.RootElement.ValueKind == JsonValueKind.Object || doc.RootElement.ValueKind == JsonValueKind.Array)
{
deserializedObject = null;
return false;
}
}
catch (JsonException)
{
// Not a JSON object or array, so it could be a raw string
deserializedObject = new HashRequest { Input = content };
return true;
}
deserializedObject = null;
return false;
}
}