Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Dev 8 posts 79 karma points
    Sep 03, 2022 @ 16:37
    Dev
    0

    How to setup custom 403 page in Umbraco 10

    Hi,

    I am struggling to setup the custom 403 page for Umbraco 10 project. Custom 404 and Error page is working fine, but for 403 it's not working. I am pasting my code below.

        app.UseExceptionHandler("/error.html");
            app.UseStatusCodePagesWithReExecute("/403.html");
    

    I am using Backoffice restrictions, that's why I need to use 403 custom page.

    Please suggest me to fix this.

  • Huw Reddick 1929 posts 6697 karma points MVP 2x c-trib
    Sep 12, 2022 @ 08:07
    Huw Reddick
    0

    In order to use app.UseStatusCodePagesWithReExecute you should create a controller that returns the correct view and use it like

    app.UseStatusCodePagesWithReExecute("/StatusPage","?code={0}");
    
    
    public class StatusPageController : Controller
    {
        public IActionResult Index(string code)
        {
            if (string.IsNullOrEmpty(code))
            {
                code = "Unknown.cshtml";
            }
            return View($"/Views/Errors/{code}.cshtml");
        }
    }
    
  • Dev 8 posts 79 karma points
    Sep 30, 2022 @ 08:04
    Dev
    0

    Thanks Huw Reddick ,

    I need to try like you mentioned above, will update here.

  • Huw Reddick 1929 posts 6697 karma points MVP 2x c-trib
    Sep 30, 2022 @ 14:08
    Huw Reddick
    0

    TBH, I didn't manage to get it to work that way :D

    What I have done is created a CustomError Document type, using that I created several error pages, error404 (assigned as the umbraco 404), errorNoAcess and errorHandler.

    These are just basic page templates with a title and message.

    I discovered that depending how the 401/403 is raised/returned, you could get an Unauthorised exception or just a http statuscode, so you have to handle both :)

    So, I create my own exceptionhandler midddleware to handle any exceptions and added some code to my startup.cs to handle the status codes

    I'll post some code when I get back home later

  • Huw Reddick 1929 posts 6697 karma points MVP 2x c-trib
    Sep 30, 2022 @ 15:41
    Huw Reddick
    1

    This is the approach I am currently using, so far it seems to work for most things :D

    Handling Errors in Umbraco 9+

  • Debasish Gracias 32 posts 163 karma points
    Oct 11, 2022 @ 07:08
    Debasish Gracias
    0

    Hi Huw Reddick,

    I'm using Umbraco version 10. I want to be able to handle 404 and 500 errors. I followed your implementation from the blog https://umbraco.themediawizards.co.uk/the-grimoire/handling-errors-in-umbraco/, but its not working. This is what I have done so far:

    1. Startup.cs

          if (env.IsDevelopment())
          {
              // app.UseDeveloperExceptionPage();
                app.CustomExceptionHandler();                
          }
      
      
      
      app.Use(async (context, next) =>
      {
          await next();
          if (context.Response.StatusCode == 404)
          {
              context.Request.Path = "/error404/";
              await next();
          }
      
      
          if (context.Response.StatusCode is 401 or 403)
          {
              context.Request.Path = "/errorNoAccess/";
              await next();
          }
      
      
          //This is a BadRequest so use the default handler (500)
          if (context.Response.StatusCode == 500)
          {
              context.Request.Path = "/error500/";
              await next();
          }
      });
      
      
      app.UseUmbraco()
          .WithMiddleware(u =>
          {
              u.UseBackOffice();
              u.UseWebsite();
          })
          .WithEndpoints(u =>
          {
              u.UseInstallerEndpoints();
              u.UseBackOfficeEndpoints();
              u.UseWebsiteEndpoints();
          });
      
      }
    2. MiddleWareExtensions.cs

    public static class MiddleWareExtensions
        {
            public static IApplicationBuilder CustomExceptionHandler(this IApplicationBuilder builder)
            {
                return builder.UseMiddleware<ExceptionMiddlewareHandler>();
            }
        }
    
    1. ExceptionMiddlewareHandler.cs
     public class ExceptionMiddlewareHandler
        {
            private readonly RequestDelegate _next;
    
            public ExceptionMiddlewareHandler(RequestDelegate next)
            {
                _next = next;
            }
    
            public async Task InvokeAsync(HttpContext context)
            {
                var allowedcodes = new[] { 200, 301, 302, 401, 403, 404, 500 };
                try
                {
                    await _next(context);
                    if (!allowedcodes.Contains(context.Response.StatusCode))
                    {
                        context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                        context.Response.Redirect("/error500");
    
                    }
                }
                catch (UnauthorizedAccessException)
                {
                    context.Response.Clear();
                    context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                    context.Response.Redirect("/errorNoAccess");
                }
                catch (Exception ex)
                {
                    if (context.Response.StatusCode is 404)
                    {
                        //may be from an exception in startup, so lets just let it get handled by the default 404;
                    }
                    else
                    {
                        context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                        context.Response.Redirect("/error500");
                    }
    
                }
            }
        }
    

    Can you please suggest what I'm doing wrong?

  • Huw Reddick 1929 posts 6697 karma points MVP 2x c-trib
    Oct 11, 2022 @ 07:35
    Huw Reddick
    0

    Hi Debasish,

    What exactly is happening when you get a 404 or raise an exception?

  • Debasish Gracias 32 posts 163 karma points
    Oct 11, 2022 @ 09:08
    Debasish Gracias
    0

    Hi Huw Reddick,

    When I enter this https://localhost:51434/testpage in the browser, I get the followingenter image description here

    It is not taking me to my custom error page.

  • Debasish Gracias 32 posts 163 karma points
    Oct 11, 2022 @ 09:14
    Debasish Gracias
    0

    Hi Huw Reddick,

    When I try to raise an exception(500 error), I'm presented with the below screen:

    enter image description here

  • Huw Reddick 1929 posts 6697 karma points MVP 2x c-trib
    Oct 11, 2022 @ 12:03
    Huw Reddick
    0

    That sounds like you haven't setup a custom404 page for umbraco yet, you need to do that first.

    https://our.umbraco.com/documentation/tutorials/Custom-Error-Pages/#create-a-404-page-in-the-backoffice

    Once that is done and working, you need to create the other error nodes using the same template as for the 404 page, you can then implement the changes to startup.cs for the custom handling

  • Debasish Gracias 32 posts 163 karma points
    Oct 12, 2022 @ 07:29
    Debasish Gracias
    0

    Yes I had not set up the custom 404 page in appsettings.json as I thought it would be handled by the custom logic you have implemented. I have added it now and 404 error handling seems to work. As I am new to this I have a couple of questions:

    1. What is the need of the below code in Startup.cs if we are setting custom 404 page in appsettings.json?

              if (context.Response.StatusCode == 404)
              {
                  context.Request.Path = "/error404/";
                  await next();
              }
      
    2. Why is the below code in place? If I comment this code, the 404 and 500 error handling still seems to work. Can you please provide some more explanation?

          if (context.Response.StatusCode == 404)
              {
                  context.Request.Path = "/error404/";
                  await next();
              }
              if (context.Response.StatusCode is 401 or 403)
              {
                  context.Request.Path = "/errorNoAccess/";
                  await next();
              }
              //This is a BadRequest so use the default handler (500)
              if (context.Response.StatusCode == 400)
              {
                  context.Request.Path = "/errorHandler/";
                  await next();
              }
      
  • Huw Reddick 1929 posts 6697 karma points MVP 2x c-trib
    Oct 12, 2022 @ 07:46
    Huw Reddick
    0
    1. I had to add that because not all 404 errors were caught by Umbraco, IIRC invalid media urls did not get picked up by the umbraco 404 redirect

    2. Similar reason to above, these errors may not get created by your code so don't get trapped by the exception handler it depends how the error/stuscode was raised.

  • Debasish Gracias 32 posts 163 karma points
    Oct 12, 2022 @ 08:26
    Debasish Gracias
    0

    Thank you Huw Reddick for the explanation. That makes sense :)

  • Jonathan Roberts 409 posts 1063 karma points
    Feb 07, 2023 @ 11:08
    Jonathan Roberts
    0

    Is there a way to redirect the user to a 404 page by throwing a 404 error and not actually redirecting them to a specific page? Our client has a tendency to rename pages so having them hard coded might lead to an incorrect 404 page

Please Sign in or register to post replies

Write your reply to:

Draft