Modify middleware response

.NET Core 3+ solution with proper resource handling: Replace response stream by MemoryStream to prevent its sending. Return the original stream after the response is modified: public async Task Invoke(HttpContext context) { var response = context.Response; //uncomment this line to re-read context.Request.Body stream //context.Request.EnableBuffering(); var originBody = response.Body; using var newBody = new MemoryStream(); response.Body … Read more

What exactly is ‘UseAuthentication()’ for?

Although this is an old thread, but since I stumbled with the same question recently I thought shedding some more light on the internals may benefit others The short answer is depends on your service type and your APIs. you don’t need to call UseAuthentication when: You implement your own middleware that handles authentication – … Read more

How to do DI in asp.net core middleware?

UserManager<ApplicationUser> is (by default) registered as a scoped dependency, whereas your CreateCompanyMiddleware middleware is constructed at app startup (effectively making it a singleton). This is a fairly standard error saying that you can’t take a scoped dependency into a singleton class. The fix is simple in this case – you can inject the UserManager<ApplicationUser> into … Read more