Reputation: 780
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
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
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