1

As off .Net 6, a middleware containing context.Request.Path = "/error/500" no longer rewrites the new path to handle the exception. Is there a new way to set a request path in .Net 6 within the middleware?

Thank you!

Attached is an example code:

   public class ErrorHandlingMiddleware
    {
        private readonly RequestDelegate next;

        public ErrorHandlingMiddleware(RequestDelegate next)
        {
            this.next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {
                await next(context);
            }
            catch (Exception ex)
            {

                context.Request.Path = "/error/500";
                await next.Invoke(context);

            }
        }

    }
Chris
  • 336
  • 4
  • 15
  • 1
    "Does not work" - please elaborate and take the [tour]. See [ask] and provide a [mre]. – Xerillio Feb 15 '22 at 14:22
  • Sorry, updated with an example. – Chris Feb 15 '22 at 14:35
  • 1
    Explain what doesn't work in the question itself. Don't make people guess what you mean. Assigning a variable or writable property won't fail. If you wanted to redirect unhandled exceptions to a specific error page, you were doing things wrong from the start. That's the job of [UseExceptionHandler](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.builder.exceptionhandlerextensions.useexceptionhandler?view=aspnetcore-6.0) – Panagiotis Kanavos Feb 15 '22 at 14:46
  • This question may lead to a [xy problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) What is the expected? Returning 500 result? Returning a view? calling a different api? – Mat Feb 15 '22 at 15:08
  • I was trying to stay away from UseExceptionHandler. I would like to have more control over the exception and route the error to the correct location. Essential, I would just like to change the path to "any" Controller/View depending on exception. This was just a broken down version of the code to figure out why it wasn't routing like it did before in .net 5. – Chris Feb 15 '22 at 15:21

1 Answers1

0

I had issues with this as well, this is what worked for me - take note of the relative vs absolute pathing:

context.Response.Redirect("/yourUrl"); // Notice leading /
context.Request.Path = "yourUrl"; //Notice lack of leading /