question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

/profiler/results 404 (Not Found)

See original GitHub issue

It’s about more than two months that i’m getting NOT FOUND error to running MiniProfiler up for asp core 3.1 I don’t know MiniProfiler conflicts with which Package.

Can you please help me to find a workaround?

Startup.cs

public class Startup
    {
        public Startup(IConfiguration configuration, IWebHostEnvironment webHostEnvironment)
        {
            Configuration = configuration;
            WebHostEnvironment = webHostEnvironment;
        }

        public IConfiguration Configuration { get; }
        public IWebHostEnvironment WebHostEnvironment { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDistributedMemoryCache();
            var secretCredentials = Configuration
                .GetSection("SecretCredentials")
                .Get<SecretCredentials>();
            services.AddSingleton(secretCredentials);
            var crashAnalytics = Configuration
                .GetSection("CrashAnalytics")
                .Get<CrashAnalytics>();
            services.AddSingleton(crashAnalytics);

            var appDbContextConnectionString = Configuration
                .GetConnectionString("ApplicationDbContextConnection");

            services.AddEntityFrameworkSqlServerNetTopologySuite();
            services.AddCustomPooledDbContextFactory<ApplicationDbContext>(options =>
           {
               options.ConnectionString = appDbContextConnectionString;
               options.Action = optionsBuilder => optionsBuilder.UseNetTopologySuite();
           });

            services.Configure<ForwardedHeadersOptions>(options =>
                options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto);

            services.AddLocalization()
            .Configure<RequestLocalizationOptions>(options =>
            {
                options.ConfigureRequestLocalization();
                options.RequestCultureProviders.Insert(0, new RouteDataRequestCultureProvider
                {
                    RouteDataStringKey = LanguageRouteConstraint.Key,
                    Options = options
                });
            });

            services.AddAuthorization(options =>
            {
                options.AddPolicy("AdminPolicy", policy =>
                    policy.RequireRole("Admin"));
            });

            services.AddHttpContextAccessor();
            var mvcBuilder = services
                .AddMvc(options =>
                {
                    options.ModelBinderProviders.Insert(0, new StringModelBinderProvider());
                    options.ModelBinderProviders.Insert(0, new DateTimeUtcModelBinderProvider());
                    options.EnableEndpointRouting = false;
                    options.SuppressAsyncSuffixInActionNames = false;
                    options.ValueProviderFactories.Insert(0, new SeparatedQueryStringValueProviderFactory());

                    options.Conventions.Add(new LocalizeActionRouteModelConvention());
                    options.Filters.Add(new MiddlewareFilterAttribute(typeof(LocalizationPipeline)));
                })
                .AddMvcLocalization()
                .AddViewLocalization()
                .AddViewOptions(options =>
                {
                    options.HtmlHelperOptions.ClientValidationEnabled = true;
                })
                .AddControllersAsServices()
                .AddJsonOptions(options =>
                {
                    options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
                    options.JsonSerializerOptions.DictionaryKeyPolicy = JsonNamingPolicy.CamelCase;
                    options.JsonSerializerOptions.IgnoreNullValues = true;
                })
                .AddNewtonsoftJson(
                    options =>
                    {
                        options.SerializerSettings.Error = R8.Lib.JsonExtensions.CustomJsonSerializerSettings.Settings.Error;
                        options.SerializerSettings.DefaultValueHandling =
                            R8.Lib.JsonExtensions.CustomJsonSerializerSettings.Settings.DefaultValueHandling;
                        options.SerializerSettings.ReferenceLoopHandling =
                            R8.Lib.JsonExtensions.CustomJsonSerializerSettings.Settings.ReferenceLoopHandling;
                        options.SerializerSettings.ObjectCreationHandling =
                            R8.Lib.JsonExtensions.CustomJsonSerializerSettings.Settings.ObjectCreationHandling;
                        options.SerializerSettings.ContractResolver =
                            R8.Lib.JsonExtensions.CustomJsonSerializerSettings.Settings.ContractResolver;
                        options.SerializerSettings.Formatting = R8.Lib.JsonExtensions.CustomJsonSerializerSettings.Settings.Formatting;
                        options.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.None;
                        options.SerializerSettings.Culture = new CultureInfo("en-US");
                    });

            if (WebHostEnvironment.IsDevelopment())
                mvcBuilder.AddRazorRuntimeCompilation();

            services.AddMvcCore(options =>
            {
                options.MaxModelValidationErrors = 50;
                options.RespectBrowserAcceptHeader = true;
            });

            services.AddCors();

            services.AddElmah(options =>
            {
                if (!WebHostEnvironment.IsDevelopment())
                    options.OnPermissionCheck = ctx => ctx.User.IsInRole(nameof(Roles.Admin));

                options.ConnectionString = appDbContextConnectionString;
            });

            services.AddAuthentication(AuthDefaults.AuthenticationScheme)
                .AddCookie(AuthDefaults.AuthenticationScheme, options =>
                  {
                      options.LoginPath = typeof(LogInModel).GetPagePath();
                      options.LogoutPath = typeof(SignOutModel).GetPagePath();
                      options.AccessDeniedPath = typeof(ErrorModel).GetPagePath(config =>
                          config.RouteDictionary = new { error = HttpStatusCode.Forbidden });
                      options.ReturnUrlParameter = PageModel.Query_CALLBACK;
                      options.ExpireTimeSpan = TimeSpan.FromDays(30);
                      options.SlidingExpiration = true;
                      options.Cookie.SameSite = SameSiteMode.Lax;
                  })
                 .AddGoogle(config =>
                 {
                     config.ClientId = secretCredentials.Google.ClientId;
                     config.ClientSecret = secretCredentials.Google.ClientSecret;
                     config.Events = new OAuthEvents
                     {
                         OnRemoteFailure = context =>
                         {
                             context.HandleResponse();
                             context.HttpContext.RiseError(context.Failure);
                             return Task.FromResult(0);
                         }
                     };
                 })
                .AddFacebook(config =>
                {
                    config.AppId = secretCredentials.Facebook.AppId;
                    config.AppSecret = secretCredentials.Facebook.AppSecret;
                    config.Events = new OAuthEvents
                    {
                        OnRemoteFailure = context =>
                        {
                            context.HandleResponse();
                            context.HttpContext.RiseError(context.Failure);
                            return Task.FromResult(0);
                        }
                    };
                });

            services.AddDataProtection();
            services.Configure<CookiePolicyOptions>(options =>
            {
                options.ConsentCookie.IsEssential = true;
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.Lax;
            });

            services.AddRouting(options =>
            {
                options.LowercaseQueryStrings = false;
                options.LowercaseUrls = true;
                options.ConstraintMap.Add(LanguageRouteConstraint.Key, typeof(LanguageRouteConstraint));
            });

            services.AddSession(options =>
            {
                options.IdleTimeout = TimeSpan.FromHours(1);
                options.Cookie.HttpOnly = true;
                options.Cookie.IsEssential = true;
            });

            services.Configure<FormOptions>(options => options.MultipartBodyLengthLimit = 838860800);

            services.AddLogging(loggingBuilder =>
            {
                loggingBuilder.AddConfiguration(Configuration.GetSection("Logging"));
                loggingBuilder.AddConsole();
                loggingBuilder.AddDebug();
            });

            services.Configure<BrotliCompressionProviderOptions>(options => options.Level = CompressionLevel.Fastest);
            services.Configure<GzipCompressionProviderOptions>(options => options.Level = CompressionLevel.Fastest);
            services
              .AddResponseCaching()
              .AddResponseCompression(options =>
              {
                  options.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
                      new[]
                      {
                              "application/javascript",
                              "application/xml",
                              "application/json",
                              "image/svg+xml"
                      });
                  options.Providers.Add<BrotliCompressionProvider>();
                  options.Providers.Add<GzipCompressionProvider>();
              });

            services.AddWebMarkupMin(
                    options =>
                    {
                        options.DisablePoweredByHttpHeaders = true;
                    })
                .AddHtmlMinification(
                    options =>
                    {
                        options.JsMinifierFactory = new NUglifyJsMinifierFactory();
                        options.CssMinifierFactory = new NUglifyCssMinifierFactory();
                        options.MinificationSettings.MinifyEmbeddedJsCode = true;
                    })
                .AddXmlMinification(options =>
                {
                    var settings = options.MinificationSettings;
                    settings.RenderEmptyTagsWithSpace = true;
                    settings.CollapseTagsWithoutContent = true;
                })
                .AddHttpCompression();

            services.AddTransient<IActionContextAccessor, ActionContextAccessor>();
            services.AddTransient<IApplicationBuilder, ApplicationBuilder>();
            services.AddScoped(x =>
            {
                var actionContext = x.GetRequiredService<IActionContextAccessor>().ActionContext;
                var factory = x.GetRequiredService<IUrlHelperFactory>();
                return factory.GetUrlHelper(actionContext);
            });

            services.AddScoped<ICulturalizedUrlHelper, CulturalizedUrlHelper>();
            services.AddTransient<ApplicationDbContext>();

            services.AddDetection();
            services.AddScoped<IGlobalService, GlobalService>();
            services.AddRequiredServices();

            var razorBuilder = services
                .AddRazorPages()
                .AddRazorPagesOptions(options =>
                {
                    options.Conventions.AuthorizeAreaFolder(nameof(Areas.User), "/");
                    options.Conventions.AuthorizeAreaFolder(nameof(Areas.Admin), "/", "AdminPolicy");
                    options.Conventions.Add(new LocalizedPageRouteModelConvention());
                });
            if (WebHostEnvironment.IsDevelopment())
                razorBuilder.AddRazorRuntimeCompilation();

            services.AddHttpClient<ICaptchaValidator, GoogleReCaptchaValidator>();

            services.AddHsts(options =>
            {
                options.Preload = true;
                options.IncludeSubDomains = true;
                options.MaxAge = TimeSpan.FromDays(365);
            });

            services.AddControllers()
                .AddXmlSerializerFormatters();

            services.AddMiniProfiler(options =>
            {
                options.ResultsListAuthorizeAsync = _ => Task.FromResult(true);
                options.ResultsAuthorizeAsync = _ => Task.FromResult(true);
                options.RouteBasePath = "/profiler";
                options.SqlFormatter = new StackExchange.Profiling.SqlFormatters.SqlServerFormatter();
                options.ResultsAuthorize = _ => !Program.DisableProfilingResults;
                options.EnableServerTimingHeader = true;
                options.ColorScheme = StackExchange.Profiling.ColorScheme.Auto;
                options.TrackConnectionOpenClose = true;
                options.IgnoredPaths.Add("/lib");
                options.IgnoredPaths.Add("/css");
                options.IgnoredPaths.Add("/js");
                options.IgnoredPaths.Add("/fonts");
                options.IgnoredPaths.Add("/img");
                options.IgnoredPaths.Add("/uploads");
            }).AddEntityFramework();

            services.AddLocalizer((serviceProvider, config) =>
            {
                using var scope = serviceProvider.CreateScope();
                var request = scope.ServiceProvider.GetService<IOptions<RequestLocalizationOptions>>();

                config.SupportedCultures = request.Value.SupportedCultures.ToList();
                config.UseMemoryCache = true;
                config.Provider = new LocalizerCustomProvider
                {
                    DictionaryAsync = () => ApplicationDbContext.GetTranslationsAsync(appDbContextConnectionString)
                };
            });

            services.AddFileHandlers((environment, options) =>
            {
                options.Path = "/uploads";
                options.HierarchicallyDateFolders = true;
                options.SaveAsRealName = false;
                options.OverwriteExistingFile = false;
                options.Runtimes.Add(new FileHandlerImageRuntime
                {
                    ImageEncoder = new JpegEncoder { Quality = 80 }
                });
                options.Runtimes.Add(new FileHandlerPdfRuntime
                {
                    GhostScriptDllPath = environment.ContentRootPath + "/gsdll64.dll",
                });
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseFileServer();
            app.UseCors(options =>
            {
                options.AllowAnyHeader();
                options.AllowAnyMethod();
                options.AllowAnyOrigin();
            });

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler(typeof(ErrorModel).GetPagePath());
                app.UseHsts();
            }

            app.UseStatusCodePagesWithReExecute(typeof(ErrorModel).GetPagePath(), "?error={0}");
            app.UseDetection();

            if (env.IsDevelopment())
                app.UseMiniProfiler();

            var provider = new FileExtensionContentTypeProvider();
            provider.Mappings[".webmanifest"] = "application/manifest+json";
            app.UseDefaultFiles();
            app.UseStaticFiles(new StaticFileOptions
            {
                ContentTypeProvider = provider,
                OnPrepareResponse = context =>
                {
                    context.Context.Response.Headers[HeaderNames.CacheControl] =
                        $"public,max-age={TimeSpan.FromDays(365).TotalMilliseconds}";
                    context.Context.Response.Headers["X-Content-Type-Options"] = "nosniff";
                    context.Context.Response.Headers.Remove("X-Powered-By");

                    string contentType = context.Context.Response.Headers["Content-Type"];
                    if (contentType == "application/x-gzip")
                    {
                        if (context.File.Name.EndsWith("js.gz"))
                        {
                            contentType = "application/javascript";
                        }
                        else if (context.File.Name.EndsWith("css.gz"))
                        {
                            contentType = "text/css";
                        }
                        context.Context.Response.Headers.Add("Content-Encoding", "gzip");
                        context.Context.Response.Headers["Content-Type"] = contentType;
                    }
                }
            });

            app.Use(async (context, next) =>
            {
                context.Response.Headers[HeaderNames.Vary] =
                    new[] { HeaderNames.AcceptEncoding };

                await next();
            });

            if (!env.IsDevelopment())
            {
                app.UseResponseCaching();
                app.UseResponseCompression();
                app.UseWebMarkupMin();
            }

            app.UseRouting();

            if (env.IsDevelopment())
                app.UseBrowserLink();

            // Who are you ?
            app.UseAuthentication();

            // Are you allowed ?
            app.UseAuthorization();
            app.UseRequestLocalization(app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>().Value);
            ServiceActivator.Configure(app.ApplicationServices);

            app.UseElmah();

            app.UseLocalizer();
            app.UseResponse();
            app.UseFileHandlers();

            app.UseSession();
            app.UseCookiePolicy();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
                endpoints.MapDefaultControllerRoute();

                endpoints.MapControllerRoute(
                    name: "Areas",
                    pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");

                endpoints.MapControllerRoute(
                    name: "Default",
                    pattern: "{" + LanguageRouteConstraint.Key + "=tr}/{controller=Home}/{action=Index}/{id?}");
            });
        }
    }

And i’ve put <miniprofiler> tag in bottom of _Layout, before </body>

But all the time i’m getting Not Found error: asd

Asp.net Core : 3.1.404 EntityFramework Core : 5.0.2 Visual Studio : 2019 16.8.4

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:10 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
Turnerjcommented, Feb 7, 2021

Just putting in my two cents - have you tried navigating to http://localhost:8080/profiler/result-index? This page lists recently profiled requests.

What I think might be happening is that the ID sent in that POST request to /profiler/results doesn’t exist in the memory storage that, by default, MiniProfiler uses. The middleware that handles /profiler/results has a few reasons it returns a 404.

If you see results, it is worth comparing what that /profiler/results request is POSTing to the server to the IDs on that page.

0reactions
iamr8commented, Feb 22, 2021

I’ve didn’t check Codes inside the commented out codes. but it seems there are some codes about MemoryCache or something about to clear memory cache ! I don’t know yet… and also still i do not know disabling these codes affecting on my project or no ! Thanks for you consideration. I’ll close this issue ❤️

Read more comments on GitHub >

github_iconTop Results From Across the Web

Miniprofiler.MVC5: "profiler/results" 404 not found when ...
The profiler works locally as expected. But when deployed on Windows server 2016 IIS 10, I get 404 not found error for "profiler/results",...
Read more >
Isolating single ASP .NET pages in ANTS Profiler results
NET page loads and unloads. This way the results can be filtered to more or less only the code that had been run...
Read more >
Error 404: 4 Ways to Fix It
Error 404 is a response code, meaning the server could not locate the requested content. Check this article to learn 4 steps to...
Read more >
Hub Topic: Thread profiler results shows nothing but exporting ...
After running a Thread Profiler and opening the results I get the following empty page (there's an "Expand 0 nodes" at the bottom):....
Read more >
Resource Profiler - Results of the Errors Category
The Resource profiler results are divided into three categories: Classes Data, Objects and Errors. When the Errors category is selected, ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found