I am logging a user's audit to the database on every page click and I thought doing this in the middleware was acceptable (And good?) as it gets fired on every HTTP request. However, when I proceed to a new page, the code in the middleware (userService.AddUser()) is being hit 3 times and I am unsure why.
Here is the code:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IUserService userService)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
// My own code.
app.Use(async (context, next) =>
{
// The database insert
userService.AddUser();
await next.Invoke();
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
I am probably missing some knowledge as of why this doesn't work.
Thanks