AT-2017
AT-2017

Reputation: 3149

Custom 404 Page Doesn't Get Redirected

I am trying to redirect to 404 custom error page whenever a user types wrong url in the browser. Say a user types https://localhost:44332/foo (foo page doesn't exist), then it should redirect to the custom error page. In my case, it doesn't, but for this, it works:

https://localhost:44332/foo/foo-page

This get redirected to custom error page. I did a small workout in my project and believe, this causes an issue for this redirection - https://localhost:44332/foo.

I've a page, say user-details which redirects with a query string something like this:

https://localhost:44332/user-details?=1002

So in the Startup.cs file, I did this to make the url user-friendly:

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<CookiePolicyOptions>(options =>
    {
        // This lambda determines whether user consent for non-essential cookies is needed for a given request.
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = SameSiteMode.None;
    });

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2).AddRazorPagesOptions(options =>
    {
        //Here is the routing done
        options.Conventions.AddPageRoute("/user-details", "{id}");
    });

    services.AddEntityFrameworkSqlite().AddDbContext<MyDbContext>();
}

So what the above code does, when a user types https://localhost:4433/1002, it gets the related details redirecting to user details page (Note: I omitted the user-details page name from the url that works fine). So now whenever I type a wrong page name that doesn't exist, say foo or whatever (https://localhost:44332/foo), instead of redirecting to error page, gets redirected to the user-details page. Anything that I missed or required to do to make it work accordingly?

N.B: Handling errors in the Startup.cs file as follows

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
   if (env.IsDevelopment())
   {
      app.UseDeveloperExceptionPage();
   }
   else
   {
      //Error handling here
      app.UseStatusCodePages();
      app.UseExceptionHandler("/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.UseMvc();
} 

Upvotes: 0

Views: 210

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239460

The problem is:

options.Conventions.AddPageRoute("/user-details", "{id}");

Just because it's named id doesn't mean that it's going to somehow only take ints. You've essentially created a route that will catch anything without an additional route segment: i.e. /foo will catch, but /foo/bar won't. You can add a constraint to help, i.e "{id:int}", which will then only catch if the route segment can be converted to an int.

Upvotes: 1

Related Questions