返回404页面没有重定向

时间:2016-08-17 12:27:29

标签: asp.net-core asp.net-core-mvc

我试图让我的404正常工作,但无法弄清楚如何正确使用它。

最初我在我的Statup配置方法中设置了以下内容:

app.UseMvc(routes =>
{
    // routing here
});

app.Use((context, next) =>
{
    context.Response.StatusCode = 404;
    return next();
});

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

哪个重定向到我显示错误的页面。但状态代码为302 > 200。我设置/error/{code}操作以返回相关的状态代码,因此现在我302 > 404(由于302重定向)使其看起来好像/error/404页面没有存在(它确实存在)。

我想要做的是返回没有重定向的错误页面,因此尝试请求/doesntexist将返回404并显示错误页面。

我尝试的另一件事是使用app.UseStatusCodePagesWithReExecute("/error/{0}");,它会在不更改网址的情况下返回404,但只显示空白页而不是我的错误页

1 个答案:

答案 0 :(得分:10)

在我的应用中,我这样做:

<script type="text/javascript">
    var CaptchaCallback = function() {
        grecaptcha.render('recaptcha1', {'sitekey' : '6Lc_your_site_key'});
        grecaptcha.render('recaptcha2', {'sitekey' : '6Lc_your_site_key'});
    };
</script>

<script src="https://www.google.com/recaptcha/api.js?onload=CaptchaCallback&render=explicit" async defer></script>

我的HomeController有这个动作方法

// custom 404 and error page - this preserves the status code (ie 404)
app.UseStatusCodePagesWithReExecute("/Home/Error/{0}");

我的观点是这样的:

public IActionResult Error(int statusCode)
{
    if (statusCode == 404)
    {
        var statusFeature = HttpContext.Features.Get<IStatusCodeReExecuteFeature>();
        if (statusFeature != null)
        {
            log.LogWarning("handled 404 for url: {OriginalPath}", statusFeature.OriginalPath);
        }

    }
    return View(statusCode);
}
如@khellang所提到的,中间件的顺序很重要,这应该在app.UseMvc之前

相关问题