mk_yo
mk_yo

Reputation: 780

ASP.NET Core Custom Middleware redirect to action not working

I'm trying to use custom middeware to handle 404 error:

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

But the needed action is not called in Error Controller:

[Route("error")]
public class ErrorController : Controller
{
    public ErrorController()
    {
    }

    [Route("404")]
    public IActionResult PageNotFound()
    {
        return View();
    }
}

I've checked that it's getting called if to make a call directly like "http:\localhost\error\404"

Upvotes: 5

Views: 4099

Answers (2)

Fei Han
Fei Han

Reputation: 27793

If possible, you can try to use the UseStatusCodePagesWithReExecute extension method to achieve your requirement.

app.UseStatusCodePagesWithReExecute("/error/{0}");

Besides, in your custom middleware code logic, you can modify the code to redirect to target url.

if (context.Response.StatusCode == 404)
{
    //context.Request.Path = "/error/404";

    context.Response.Redirect("/error/404");
    return;
}

Upvotes: 3

Bryan Lewis
Bryan Lewis

Reputation: 5977

I'm not positive, but I think you need to pass in the HttpContext to your call to next(). I haven't had a chance to test this. Try changing to this:

if (context.Response.StatusCode == 404)
{
    context.Request.Path = "/error/404";
    await context.Next(context.HttpContext);
}

Upvotes: 1

Related Questions