-
Notifications
You must be signed in to change notification settings - Fork 18
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Make developer exception page work during dev in the sample
- Loading branch information
1 parent
c6f6438
commit 747e70c
Showing
3 changed files
with
66 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
52 changes: 52 additions & 0 deletions
52
samples/RazorSlices.Samples.WebApp/ResponseBufferingMiddleware.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
namespace RazorSlices.Samples.WebApp; | ||
|
||
using System.IO; | ||
using System.Threading.Tasks; | ||
using Microsoft.AspNetCore.Builder; | ||
using Microsoft.AspNetCore.Http; | ||
|
||
internal sealed class ResponseBufferingMiddleware(RequestDelegate next) | ||
{ | ||
public async Task InvokeAsync(HttpContext context) | ||
{ | ||
// Save the original response body stream | ||
var originalBodyStream = context.Response.Body; | ||
|
||
try | ||
{ | ||
// Create a memory stream to buffer the response | ||
using var memoryStream = new MemoryStream(); | ||
context.Response.Body = memoryStream; | ||
|
||
// Call the next middleware | ||
await next(context); | ||
|
||
// If no exception occurs, write the buffered response to the original body | ||
memoryStream.Seek(0, SeekOrigin.Begin); | ||
await memoryStream.CopyToAsync(originalBodyStream); | ||
} | ||
catch | ||
{ | ||
// Clear the existing response | ||
context.Response.Clear(); | ||
context.Response.StatusCode = StatusCodes.Status500InternalServerError; | ||
|
||
// Rethrow to let the Developer Exception Page middleware handle it | ||
throw; | ||
} | ||
finally | ||
{ | ||
// Restore the original body stream | ||
context.Response.Body = originalBodyStream; | ||
} | ||
} | ||
} | ||
|
||
internal static class ResponseBufferingMiddlewareExtensions | ||
{ | ||
public static IApplicationBuilder UseResponseBuffering(this IApplicationBuilder app) | ||
{ | ||
return app.UseMiddleware<ResponseBufferingMiddleware>(); | ||
} | ||
} | ||
|