Last active
May 26, 2022 12:39
-
-
Save alexjamesbrown/758b083f257821a132601071f4519f79 to your computer and use it in GitHub Desktop.
Using RegisterForDispose to do something after the response has been sent
This file contains hidden or 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
public class Startup | |
{ | |
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) | |
{ | |
app.Use | |
( | |
async (context, next) => | |
{ | |
Console.WriteLine("Hello from middleware"); | |
await next.Invoke(); | |
} | |
); | |
// RegisterForDispose | |
app.Use | |
( | |
async (context, next) => | |
{ | |
context.Response.RegisterForDispose(new SneakyMethodToRunAfterResponse()); | |
await next(); | |
} | |
); | |
app.UseHttpsRedirection(); | |
app.UseRouting(); | |
app.UseEndpoints(endpoints => | |
{ | |
endpoints.MapGet("/", async context => | |
{ | |
Console.WriteLine("Hello from endpoint"); | |
await context.Response.WriteAsync("Hello World!"); | |
}); | |
}); | |
} | |
} | |
public class SneakyMethodToRunAfterResponse : IDisposable | |
{ | |
public void Dispose() | |
{ | |
Console.WriteLine("Hello from the afterlife"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment