Diegos
Diegos

Reputation: 115

UseStatusCodePagesWithReExecute() not working on .NET Core 3.1

I use UseStatusCodePagesWithReExecute to redirect the user to an error page if there is a problem with the application.

If an Error occurs in my application for example Code 500, I am not redirected to "/Home/Error". If I call it manually "/Home/Error" is ok!

Here is my code, where is the error?

        public IActionResult Error(string code)
        {
            return View(new ErrorModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier, ErrorStatusCode = code });
        }



public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseSiteOfflineMiddleware(); 

            app.UseStatusCodePagesWithReExecute("/Home/Error", "?code={0}");

            app.UseStaticFiles();
            app.UseRouting();

            app.UseAuthentication(); 
            app.UseAuthorization();
            app.UseSession(); // Aggiungi Supporto Sessioni

            // Dependency Injection Option per leggere Localizzazione File Resources delle lingue
            var localizationOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>().Value;
            app.UseRequestLocalization(localizationOptions);

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "products",
                    pattern: "{codLanguage}/shop/{id}/{nameProduct}",
                    new { controller = "Catalog", action = "Detail" });

                endpoints.MapControllerRoute(
                    name: "catalog",
                    pattern: "/shop",
                    new { controller = "Catalog", action = "Index" });

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


            app.Run(async (context) =>
            {
                await Task.CompletedTask;
            });

        }

Upvotes: 4

Views: 6742

Answers (1)

Yiyi You
Yiyi You

Reputation: 18179

In the issue, as Tratcher mentioned,UseStatusCodePagesWithReExecute is for status code responses without bodies (e.g empty 404).And for the code like 500,you can use UseExceptionHandler.

If you want to redirect to the url "/Home/Error" when the status code is 500, you can do like this:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
           app.UseExceptionHandler("/Home/Error");
            app.UseStatusCodePagesWithReExecute("/Home/Error", "?code={0}");

Upvotes: 5

Related Questions