Custom 404 Page Doesn't Get Redirected

泄露秘密 提交于 2019-12-11 18:04:08

问题


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();
} 

回答1:


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.



来源:https://stackoverflow.com/questions/57858067/custom-404-page-doesnt-get-redirected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!