Skip to content
This repository was archived by the owner on Nov 25, 2025. It is now read-only.

Commit 8e1713f

Browse files
author
Ihar Yakimush
committed
json body
1 parent 41c49ee commit 8e1713f

File tree

4 files changed

+60
-21
lines changed

4 files changed

+60
-21
lines changed

Commmunity.AspNetCore.ExceptionHandling.Integration/Startup.cs

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -31,21 +31,20 @@ public void ConfigureServices(IServiceCollection services)
3131
services.AddExceptionHandlingPolicies(options =>
3232
{
3333
options.For<DuplicateNameException>().Retry().NextChain();
34+
3435
options.For<DuplicateWaitObjectException>().Retry();
3536

3637
options.For<ArgumentOutOfRangeException>().Log().Rethrow();
3738

3839
options.For<InvalidCastException>()
3940
.Response(e => 400)
40-
.WithHeaders((h, e) => h["X-qwe"] = e.Message)
41-
.WithBody((req,stream, exception) =>
42-
{
43-
using (StreamWriter sw = new StreamWriter(stream))
44-
{
45-
return sw.WriteAsync(exception.ToString());
46-
}
41+
.Headers((h, e) => h["X-qwe"] = e.Message)
42+
.WithBody((req,sw, exception) =>
43+
{
44+
return sw.WriteAsync(exception.ToString());
4745
})
4846
.NextChain();
47+
4948
options.For<Exception>()
5049
.Log(lo => { lo.Formatter = (o, e) => "qwe"; })
5150
.Response(e => 500, RequestStartedBehaviour.SkipHandler).ClearCacheHeaders().WithBodyJson((r, e) => new { msg = e.Message, path = r.Path })

Commmunity.AspNetCore.ExceptionHandling/ExceptionHandlingPolicyMiddleware.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,8 @@ private async Task InvokeWithRetryAsync(HttpContext context, RequestDelegate nex
172172
iteration,
173173
context.TraceIdentifier);
174174

175+
context.Response.Headers.Clear();
176+
175177
await InvokeWithRetryAsync(context, next, logger, iteration + 1);
176178
}
177179

Commmunity.AspNetCore.ExceptionHandling/PolicyBuilderExtensions.cs

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,7 @@ public static IResponseHandlers<TException> Response<TException>(
136136
return builder as IResponseHandlers<TException>;
137137
}
138138

139-
public static IResponseHandlers<TException> WithHeaders<TException>(
139+
public static IResponseHandlers<TException> Headers<TException>(
140140
this IResponseHandlers<TException> builder, Action<IHeaderDictionary,TException> settings, int index = -1)
141141
where TException : Exception
142142
{
@@ -180,22 +180,19 @@ public static IResponseHandlers<TException> ClearCacheHeaders<TException>(
180180
}
181181

182182
public static IResponseHandlers<TException> WithBody<TException>(
183-
this IResponseHandlers<TException> builder, Func<HttpRequest, Stream, TException, Task> settings, int index = -1)
183+
this IResponseHandlers<TException> builder, Func<HttpRequest, StreamWriter, TException, Task> settings, int index = -1)
184184
where TException : Exception
185185
{
186186
if (settings == null)
187187
{
188188
throw new ArgumentNullException(nameof(settings));
189-
}
189+
}
190190

191191
builder.Services.Configure<RawResponseHandlerOptions<TException>>(responceOptions =>
192192
{
193193
responceOptions.SetResponse.Add((context, exception) =>
194194
{
195-
if (context.Response.Body.CanSeek)
196-
context.Response.Body.SetLength(0L);
197-
198-
return settings(context.Request,context.Response.Body, exception);
195+
return RawResponseExceptionHandler<TException>.SetBody(context, exception, settings);
199196
});
200197
});
201198

@@ -206,7 +203,7 @@ public static IResponseHandlers<TException> WithBodyJson<TException, TObject>(
206203
this IResponseHandlers<TException> builder, Func<HttpRequest, TException, TObject> value, JsonSerializerSettings settings = null, int index = -1)
207204
where TException : Exception
208205
{
209-
return builder.WithBody((request, stream, exception) =>
206+
return builder.WithBody((request, streamWriter, exception) =>
210207
{
211208
if (settings == null)
212209
{
@@ -226,12 +223,23 @@ public static IResponseHandlers<TException> WithBodyJson<TException, TObject>(
226223
headers[HeaderNames.ContentType] = "application/json";
227224
}
228225

229-
using (TextWriter textWriter = new StreamWriter(stream))
226+
TObject val = value(request, exception);
227+
228+
//return Task.CompletedTask;
229+
using (MemoryStream ms = new MemoryStream())
230230
{
231-
jsonSerializer.Serialize(textWriter, value(request, exception));
232-
}
231+
using (StreamWriter sw = new StreamWriter(ms, streamWriter.Encoding, 1024, true))
232+
{
233+
jsonSerializer.Serialize(sw, val);
234+
}
233235

234-
return Task.CompletedTask;
236+
ms.Seek(0, SeekOrigin.Begin);
237+
byte[] array = ms.ToArray();
238+
BinaryWriter binaryWriter = new BinaryWriter(streamWriter.BaseStream, streamWriter.Encoding, true);
239+
binaryWriter.Write(array);
240+
241+
return Task.CompletedTask;
242+
}
235243
});
236244
}
237245
}

Commmunity.AspNetCore.ExceptionHandling/Response/RawResponseExceptionHandler.cs

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
using System;
2+
using System.IO;
23
using System.Net;
4+
using System.Text;
35
using System.Threading;
46
using System.Threading.Tasks;
7+
using Commmunity.AspNetCore.ExceptionHandling.Builder;
58
using Commmunity.AspNetCore.ExceptionHandling.Handlers;
69
using Commmunity.AspNetCore.ExceptionHandling.Logs;
710
using Microsoft.AspNetCore.Http;
@@ -15,6 +18,8 @@ public class RawResponseExceptionHandler<TException> : HandlerStrongType<TExcept
1518
{
1619
public const string StatusCodeSetKey = "5D1CFED34A39";
1720

21+
public const string BodySetKey = "6D1CFED34A39";
22+
1823
private readonly RawResponseHandlerOptions<TException> _options;
1924

2025
private static readonly EventId ResponseHasStarted = new EventId(127, "ResponseAlreadyStarted");
@@ -40,8 +45,7 @@ protected override async Task<HandlerResult> HandleStrongType(HttpContext httpCo
4045
else
4146
{
4247
return HandlerResult.NextHandler;
43-
}
44-
48+
}
4549
}
4650

4751
await HandleResponseAsync(httpContext, exception);
@@ -78,5 +82,31 @@ public static Task SetStatusCode(HttpContext context, TException exception, Func
7882

7983
return Task.CompletedTask;
8084
}
85+
86+
public static Task SetBody<TException>(HttpContext context, TException exception, Func<HttpRequest, StreamWriter, TException, Task> settings)
87+
where TException : Exception
88+
{
89+
if (!context.Items.ContainsKey(BodySetKey))
90+
{
91+
context.Items[BodySetKey] = true;
92+
93+
Stream stream = context.Response.Body;
94+
95+
if (stream.CanSeek)
96+
{
97+
stream.Seek(0, SeekOrigin.Begin);
98+
//stream.SetLength(0);
99+
}
100+
101+
if (stream.CanWrite)
102+
{
103+
StreamWriter writer = new StreamWriter(stream,Encoding.UTF8,1024, true);
104+
105+
return settings(context.Request, writer, exception);
106+
}
107+
}
108+
109+
return Task.CompletedTask;
110+
}
81111
}
82112
}

0 commit comments

Comments
 (0)