0

使用属性路由在 MVC 5 中实现 404(例如)错误页面的最佳方法是什么?

我读过这篇文章:http ://benfoster.io/blog/aspnet-mvc-custom-error-pages

对于一个简单的 404 重定向来说,这似乎有点牵强!!

我有一个名为 Notify 的控制器:

[RoutePrefix("notify")]
public class NotifyController : Controller
{
    [Route("not-found")] 
    public ActionResult NotFound()
    {
        return View();
    }
}

在我的 web.config 中:

<customErrors mode="On" defaultRedirect="~/notify/error" xdt:Transform="Replace">
      <error statusCode="404" redirect="~/notify/not-found"/>
</customErrors>

如果我输入一个狡猾的 URL,我会得到如下所示的未找到页面: https ://www.mydomain.co.uk/notify/not-found?aspxerrorpath=/lkl

我链接到的文章建议将以下内容添加到 CustomErrors 以删除 aspxerrorpath:

redirectMode="ResponseRewrite"

但是,这会破坏重定向。因此,如果我忽略它,它仍然会重定向但不会返回 404 状态。所以我将我的 ActionResult 更改为:

[Route("not-found")] 
public ActionResult NotFound()
{
    if (Response.StatusCode == 200)
            Response.StatusCode = 404; 
        return View();
}

这抛出了 404 状态代码,但给了我默认的 404 错误页面!

是否有推荐的方法来使用属性路由处理 MVC 中的 CustomErrors?或者我是否需要像链接中那样处理 aspx 页面?

4

0 回答 0