.Net Core Middleware hitting multiple times on page request

Viewed 2096

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

1 Answers

It's being called multiple times due to images not being found on said page.

In the console of the browser, a third party library cannot find an image which is calling a 404.

sort_both.png:1 Failed to load resource: the server responded with a status of 404 ()

If this happens to you, I would check the console window in case images and or files are missing.

Related