locked
NotFound Page in Asp.net Core RRS feed

  • Question

  • User338455301 posted

    Hi,

    i want design 404 page in my project and i have use culture root ,

    my startup

     app.Use(async (context, next) =>
                {
                    await next();
                    if (context.Response.StatusCode == 404)
                    {
                        context.Request.Path = "fa/error_404";
                        await next();
                    }
                });
    
     app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllers();
    
                    endpoints.MapControllerRoute(
                    name: "areas",
                    pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
    
                    endpoints.MapControllerRoute(
                        name: "default",
                        pattern: "{culture=fa}/{controller=Home}/{action=Index}/{id?}");
    
    
    
                });
     [Route("/error_404")]
            [Route("{culture}/error_404")]
            public async Task<IActionResult> AboutUs()
            {           
                return View();
            }

    my default url is /fa

    but when i search a not exsits url for example  /fa/Jfejsfd    its not got error_404 action and return not found




    Monday, April 13, 2020 8:57 AM

Answers

  • User711641945 posted

    Hi elahi1mahdi,

    Your route attribute is `[Route("/fa/error4")]`,why did you request the url  like below:

    context.Request.Path = "/fa/error_404";

    It should be `/fa/error4`.

    context.Request.Path = "/fa/error4";

    What is your RouteCultureProvider?

    Best Regards,

    Rena

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, April 16, 2020 9:09 AM

All replies

  • User-18289217 posted

    what happens if you disable status code pages?

    statusCodePagesFeature.Enabled = false;

    Monday, April 13, 2020 9:13 AM
  • User338455301 posted
     app.Use(async (context, next) =>
                {
                    var statusCodePagesFeature = context.Features.Get<IStatusCodePagesFeature>();
                    if (statusCodePagesFeature != null)
                    {
                        statusCodePagesFeature.Enabled = false;
                    }
                    await next();
                    if (context.Response.StatusCode == 404)
                    {
                        context.Request.Path = "/fa/about-us";
                        await next();
                    }
                });

    i replaced this code but not worked and show not found page 

    by the way when i replaced change route in startup to 

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

    remove the culture and search not exsist page example: /iuiewjzxd  its worked 
    but i want have culture route

    Monday, April 13, 2020 9:54 AM
  • User711641945 posted

    Hi elahi1mahdi,

    You add route attribute on your action,so the default route template does not work:

    [Route("/error_404")]
    [Route("{culture}/error_404")]

    Change like below:

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/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.Use(async (context, next) =>
        {
            var statusCodePagesFeature = context.Features.Get<IStatusCodePagesFeature>();
            if (statusCodePagesFeature != null)
            {
                statusCodePagesFeature.Enabled = false;
            }
            await next();
            if (context.Response.StatusCode == 404)
            {
                context.Request.Path = "/fa/error_404";
                await next();
            }
        });
        app.UseHttpsRedirection();
        app.UseStaticFiles();
    
        app.UseRouting();
    
        app.UseAuthorization();
              
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
            name: "areas",
            pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
    
            endpoints.MapControllerRoute(
                name: "culture",
                pattern: "{culture=fa}/{controller=Home}/{action=Index}/{id?}");
    
        });
    }

    Best Regards,

    Rena

    Tuesday, April 14, 2020 8:20 AM
  • User338455301 posted

    i change it but its now worked

    Wednesday, April 15, 2020 10:38 AM
  • User711641945 posted

    Hi elahi1mahdi,

    i change it but its now worked

    So you do not get into the AboutUs action by using my code,right?What does the result you get?A default 404 page?

    What is your controller like which contains the AboutUs action?Please share more details about the controller,for example,if it contains route attribute with culture or not.

    I suggest that you could share your whole Startup.cs,due to the order of the middleware may cause the issue.

    Best Regards,

    Rena

    Thursday, April 16, 2020 5:29 AM
  • User338455301 posted

    i get a default 404 page 
     my problem with route culture
    its my codes when i add route culture and cant find action

    StartUp.cs

    public void ConfigureServices(IServiceCollection services)
            {
    
                services.AddDbContext<ApplicationDbContext>(options =>
                    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), c => c.MigrationsAssembly("DataLayer")));
    
                services.AddIdentity<ApplicationUser, ApplicationRole>(options =>
                {
                    options.Password.RequiredLength = 6;
                    options.Password.RequireLowercase = false;
                    options.Password.RequireUppercase = false;
                    options.Password.RequireNonAlphanumeric = false;
                    options.Password.RequireDigit = false;
                })
                    .AddEntityFrameworkStores<ApplicationDbContext>()
                    .AddDefaultTokenProviders();
    
                //services.AddTransient<DbContextSeedData>();
                services.AddDistributedMemoryCache();
    
                services.AddSession(options =>
                {
                    // Set a short timeout for easy testing.
                    options.IdleTimeout = TimeSpan.FromDays(1);
                    options.Cookie.HttpOnly = true;
                    // Make the session cookie essential
                    options.Cookie.IsEssential = true;
                });
                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;
                });
                // Add application services.
                services.AddLocalization(options => options.ResourcesPath = "Resources");
                services.AddControllersWithViews(options =>
                {
                    options.Filters.Add(typeof(DynamicAuthorizationFilter));
                }).AddRazorRuntimeCompilation().AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix,
                options => options.ResourcesPath = "Resources"
               ).AddDataAnnotationsLocalization();
    
                services.AddBrowserDetection();
               
    
    
            }
    
            // 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();
                    app.UseDatabaseErrorPage();
                }
                else
                {
                    app.UseExceptionHandler("/Home/Error");
                    app.UseHsts();
    
                }
    
                FileExtensionContentTypeProvider contentTypes = new FileExtensionContentTypeProvider();
                contentTypes.Mappings[".apk"] = "application/vnd.android.package-archive";
    
                app.UseHttpsRedirection();
    
                app.UseStaticFiles(new StaticFileOptions
                {
                    OnPrepareResponse = context =>
                    {
                        // Cache static file for 1 year
                        if (!string.IsNullOrEmpty(context.Context.Request.Query["v"]))
                        {
                            context.Context.Response.Headers.Add("cache-control", new[] { "public,max-age=31536000" });
                            context.Context.Response.Headers.Add("Expires", new[] { DateTime.UtcNow.AddYears(1).ToString("R") }); // Format RFC1123
                        }
                    }
                });
                app.Use(async (context, next) =>
                {
                    await next();
                    if (context.Response.StatusCode == 404)
                    {
                        context.Request.Path = "/fa/error_404";
                        await next();
                    }
                });
    
                app.UseCookiePolicy();
    
                app.UseRouting();
    
                app.UseAuthentication();
                app.UseAuthorization();
    
                app.UseSession();
                //app.UseMiddleware<HandleCultureUrl>();
    
                var supportedCultures = new List<CultureInfo>()
                {
                    new CultureInfo("fa"),
                    new CultureInfo("en")
                };
                var options = new RequestLocalizationOptions()
                {
                    DefaultRequestCulture = new RequestCulture("fa"),
                    SupportedCultures = supportedCultures,
                    SupportedUICultures = supportedCultures,
                    RequestCultureProviders = new List<IRequestCultureProvider>()
                    {
                        new QueryStringRequestCultureProvider(),
                        new CookieRequestCultureProvider()
                    }
    
                };
                options.RequestCultureProviders.Insert(0, new RouteCultureProvider(options.DefaultRequestCulture));
            
              
    
                app.UseRequestLocalization(options);
               
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllers();
    
                    endpoints.MapControllerRoute(
                    name: "areas",
                    pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
    
                    endpoints.MapControllerRoute(
                        name: "default",
                        pattern: "{culture=fa}/{controller=Home}/{action=Index}/{id?}");
    
                 
                    endpoints.MapRazorPages();
    
    
                });
    
    
            }
    }

    and my controller

     public class ErrorController : Controller
        {
            [Route("/fa/error4")]
            public async Task<IActionResult> Error_404()
            {
                return View();
            }
    
        }

    its worked when i change to this codes 

    remove culture

     endpoints.MapControllerRoute(
                        name: "default",
                        pattern: "{culture=fa}/{controller=Home}/{action=Index}/{id?}");

    and remove route attribute from error controller

     [Route("/fa/error4")]
            public async Task<IActionResult> Error_404()
            {
                return View();
            }

    and change address in startup


     app.Use(async (context, next) =>
                {
                    await next();
                    if (context.Response.StatusCode == 404)
                    {
                        context.Request.Path = "/Error/Error_404";
                        await next();
                    }
                });
    

    with this change and remove culture its woked but i want use culture



    Thursday, April 16, 2020 6:14 AM
  • User711641945 posted

    Hi elahi1mahdi,

    Your route attribute is `[Route("/fa/error4")]`,why did you request the url  like below:

    context.Request.Path = "/fa/error_404";

    It should be `/fa/error4`.

    context.Request.Path = "/fa/error4";

    What is your RouteCultureProvider?

    Best Regards,

    Rena

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, April 16, 2020 9:09 AM
  • User338455301 posted

    Thanks For Your Help

    Saturday, April 18, 2020 6:00 AM