Search code examples
asp.net-coreazure-web-app-serviceasp.net-core-2.2

ASP.Net Core 2.2 Does not render complete HTML on Azure webApp


I have an ASP.Net Core 2.2 webapp running and this one works pretty much ok most of the time, however from time to time it just stops rendering HTML at a random place in the HTML Document. This only occurs in azure environment, locally it runs fine!!

I've been looking at this stuff for days now and I'm running out of ideas.

Some context:

  • It's running In Process mode (out process also failed).
  • it's loadbalanced, I've checked all instances and they seem healthy.
  • It does some async processing in Controller but all calls are awaited for.
  • I've checked errorlogs, diagnostics, everything, I just can't find the problem.

Program.cs

 public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .ConfigureKestrel(options => {
                        options.AddServerHeader = false;
                        options.Limits.MaxRequestBodySize = 52428800;

                }
                )
                .UseIISIntegration()
                .UseStartup<Startup>()
                .UseUrls("http://localhost:44309", "https://0.0.0.0:44310")
                .Build();
    }

Startup.cs

    [SuppressMessage("ReSharper", "UnusedMember.Global")]
    [SuppressMessage("ReSharper", "ClassNeverInstantiated.Global")]
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {

            Configuration = configuration;
        }

        private IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {


            services.RegisterProviders(Configuration);

            services.AddMvc(opts =>
            {
                opts.Filters.Add(typeof(AdalTokenAcquisitionExceptionFilter));
            }).AddRazorPagesOptions(options =>
            {
                options.Conventions.AllowAnonymousToPage("/error");
                options.Conventions.AllowAnonymousToFolder("/app");
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
               .AddJsonOptions(options =>
               {
                   options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                   options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
               }
            );

            services.ConfigureExternalCookie(options =>
            {
                options.Cookie.SameSite = SameSiteMode.None;
            }); services.ConfigureApplicationCookie(options =>
            {
                options.Cookie.SameSite = SameSiteMode.None;
            });

            services.AddAuthentication(sharedOptions =>
                {
                    sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
                    sharedOptions.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                })
                .AddCookie(c =>
                {
                    c.SessionStore = new RedisCacheTicketStore(services.BuildServiceProvider().GetService<IDistributedCache>());
                    c.Cookie.Name = "snps";
                    c.Cookie.SameSite = SameSiteMode.None; // if changing Safari keeps redirecting back and forth when signin at microsoftonline.com ...
                })
                .AddAzureAd(options =>
                {
                    Configuration.Bind("AzureAd", options);
                }, Configuration);

            services.AddCors();



            services.AddNodeServices(options =>
            {
                options.LaunchWithDebugging = true;
                options.DebuggingPort = 9229;
            });

            //Add distributed cache service backed by Redis cache
            services.AddDistributedRedisCache(o =>
            {
                o.Configuration = Configuration.GetConnectionString("RedisCache");
            });

            services.Configure<CookieTempDataProviderOptions>(options =>
            {
                options.Cookie.Name = "tmp";
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                try
                {
                    //app.UseExceptionHandler("/Error");
                    app.UseDeveloperExceptionPage();
                    app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
                    {
                        ConfigFile = "./webpack.development.config.js",
                        HotModuleReplacement = true,
                        HotModuleReplacementServerPort = 8082

                    });
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                    Debug.WriteLine(ex.StackTrace);
                }
            }
            else
            {
                app.UseExceptionHandler("/Error");

            }

            app.UseCookiePolicy(new CookiePolicyOptions
            {
                MinimumSameSitePolicy = SameSiteMode.None // else safari ends up in an infinite loop when signing in
            });

            var provider = new FileExtensionContentTypeProvider();
            provider.Mappings[".ttf"] = "application/octet-stream";
            app.UseDefaultFiles();
            app.UseStaticFiles(new StaticFileOptions
            {
                ContentTypeProvider = provider
            });
            app.UseAuthentication();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");


                routes.MapRoute("signin", "signin", defaults: new { controller = nameof(HomeController), action = "SignIn" });

                routes.MapSpaFallbackRoute(
                    name: "spa-fallback",
                    defaults: new { controller = "Home", action = "Index" });
            });

        }
    }


Solution

  • Congratulation that you have found the solutions:

    Turns out Application Insights config in Application Settings was causing all problems. This application setting APPINSIGHTS_JAVASCRIPT_ENABLED = true was caused it.

    I post this as answer and this can be beneficial to other community members.