Home > database >  Custom 404 page redirect loops in a infinite loop
Custom 404 page redirect loops in a infinite loop

Time:09-22

My problem is when I go to my website.com/adsadasdsad I get redirected to /Error/404 for like 20 times until the browser gives up. My code is:

Startup.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace _projectname
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

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

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.Use(async (ctx, next) =>
                {
                    await next();

                    if (ctx.Response.StatusCode == 404 && !ctx.Response.HasStarted)
                    {
                        //Re-execute the request so the user gets the error page
                        string originalPath = ctx.Request.Path.Value;
                        ctx.Items["originalPath"] = originalPath;
                        ctx.Request.Path = "/Error";
                        await next();
                    }
                });
                // orig
                System.Diagnostics.Debug.WriteLine("bah");
                //app.UseExceptionHandler("/Error/{0}");
                app.UseStatusCodePagesWithRedirects("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

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

In this code above I tried using app.UseExceptionHandler AND app.UseStatusCodePagesWithRedirects interchangably with no results.

My Error controller:

using Microsoft.AspNetCore.Mvc;

namespace _projectname.Error;

public class ErrorController : Controller
{
    [Route("/Error/{statusCode}")]
    public IActionResult HttpStatusCodeHandler(int statusCode)
    {
        switch (statusCode)
        {
            case 404:
                System.Diagnostics.Debug.WriteLine("bah");
                ViewBag.ErrorMessage("Resource could not be found.");
                break;
            case 500:
                break;
        }
        return View("Error");
    }
}

I don't get what I'm doing wrong. The redirect seems to loop even if I change my redirect URLs and breakpoints don't seem to work in my Visual Studio 2022 Preview. Also there is no output it seems.

My launchSettings.json is the following:

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:28725",
      "sslPort": 44342
    }
  },
  "profiles": {
    "_34digital.ruhr": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "applicationUrl": "https://localhost:5001;http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Production"
      }
    },
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Production"
      }
    }
  }
}

P.S. yes, I do have a shared Error.cshtml and a Folder named "Error" with 404.cshtml and 500.cshtml

CodePudding user response:

The mistake was that the Error Folder was not in the Pages folder (facepalm)

  • Related