11
11
using Microsoft . AspNetCore . Builder ;
12
12
using Microsoft . AspNetCore . Http ;
13
13
using Microsoft . AspNetCore . Http . Features ;
14
+ using Microsoft . AspNetCore . Http . Json ;
15
+ using Microsoft . Extensions . Options ;
14
16
15
17
namespace Benchmarks . Middleware
16
18
{
@@ -20,25 +22,22 @@ public class JsonMiddleware
20
22
private const int _bufferSize = 27 ;
21
23
22
24
private readonly RequestDelegate _next ;
25
+ private readonly JsonSerializerOptions _jsonOptions ;
23
26
24
- public JsonMiddleware ( RequestDelegate next ) => _next = next ;
27
+ public JsonMiddleware ( RequestDelegate next , IOptions < JsonOptions > jsonOptions )
28
+ {
29
+ _next = next ;
30
+ _jsonOptions = jsonOptions . Value . SerializerOptions ;
31
+ }
25
32
26
33
public Task Invoke ( HttpContext httpContext )
27
34
{
28
35
if ( httpContext . Request . Path . StartsWithSegments ( _path , StringComparison . Ordinal ) )
29
36
{
30
37
httpContext . Response . StatusCode = 200 ;
31
- httpContext . Response . ContentType = "application/json" ;
32
38
httpContext . Response . ContentLength = _bufferSize ;
33
39
34
- var syncIOFeature = httpContext . Features . Get < IHttpBodyControlFeature > ( ) ;
35
- if ( syncIOFeature != null )
36
- {
37
- syncIOFeature . AllowSynchronousIO = true ;
38
- }
39
-
40
- return JsonSerializer . SerializeAsync < JsonMessage > ( httpContext . Response . Body , new JsonMessage { message = "Hello, World!" } ,
41
- CustomJsonContext . Default . JsonMessage ) ;
40
+ return httpContext . Response . WriteAsJsonAsync < JsonMessage > ( new JsonMessage { message = "Hello, World!" } , _jsonOptions , httpContext . RequestAborted ) ;
42
41
}
43
42
44
43
return _next ( httpContext ) ;
@@ -50,7 +49,7 @@ public static class JsonMiddlewareExtensions
50
49
public static IApplicationBuilder UseJson ( this IApplicationBuilder builder ) => builder . UseMiddleware < JsonMiddleware > ( ) ;
51
50
}
52
51
53
- [ JsonSourceGenerationOptions ]
52
+ [ JsonSourceGenerationOptions ( PropertyNamingPolicy = JsonKnownNamingPolicy . CamelCase ) ]
54
53
[ JsonSerializable ( typeof ( JsonMessage ) ) ]
55
54
internal partial class CustomJsonContext : JsonSerializerContext
56
55
{
0 commit comments