如何将中间件配置为仅重定向 404 状态代码
How can I configure the middleware to only redirect for a 404 status code
我想在遇到 404 时重定向到特定页面。
我尝试了几个教程和 StatusCodePages,但没有任何效果。
有没有人有 Core 3.1 的示例,它只重定向 404 而不是所有状态代码?
这里有几个选项,它们都应该在 .Net Core 中工作。将此添加到 web.config 文件:
<customErrors mode="Off">
<error statusCode="404" redirect="~/errorPages/PageNotFound.aspx" />
</customErrors>
或者您可以只在 Startup.cs 中添加自己的中间件,而不是使用诊断包:
app.Use(async (context, next) =>
{
if(context.Response.Status == 404)
{
// return page
}
else
{
await next.Invoke();
}
// loggin
});
很简单。
app.UseStatusCodePagesWithReExecute("/Home/Error/{0}");
对于此示例,在您的家庭控制器中,创建一个名为 Error 的方法,该方法接受一个整数。
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
[Route("Home/Error/{statusCode}")]
public IActionResult Error(int statusCode)
{
var error = new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier };
// Error caused by something other than a 404 should not be processed here.
if (statusCode != 404)
{
return View(error);
}
// Logic that handles 404 errors goes here.
}
现在,所有异常都将路由到此方法,但通过检查状态代码,您可以对 404 错误有一些特定的逻辑。
我想在遇到 404 时重定向到特定页面。
我尝试了几个教程和 StatusCodePages,但没有任何效果。
有没有人有 Core 3.1 的示例,它只重定向 404 而不是所有状态代码?
这里有几个选项,它们都应该在 .Net Core 中工作。将此添加到 web.config 文件:
<customErrors mode="Off">
<error statusCode="404" redirect="~/errorPages/PageNotFound.aspx" />
</customErrors>
或者您可以只在 Startup.cs 中添加自己的中间件,而不是使用诊断包:
app.Use(async (context, next) =>
{
if(context.Response.Status == 404)
{
// return page
}
else
{
await next.Invoke();
}
// loggin
});
很简单。
app.UseStatusCodePagesWithReExecute("/Home/Error/{0}");
对于此示例,在您的家庭控制器中,创建一个名为 Error 的方法,该方法接受一个整数。
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
[Route("Home/Error/{statusCode}")]
public IActionResult Error(int statusCode)
{
var error = new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier };
// Error caused by something other than a 404 should not be processed here.
if (statusCode != 404)
{
return View(error);
}
// Logic that handles 404 errors goes here.
}
现在,所有异常都将路由到此方法,但通过检查状态代码,您可以对 404 错误有一些特定的逻辑。