7

我需要在 MVC 4 中实现我自己的自定义错误页面。基本上,当用户尝试查看Details任何产品 ID 不存在的产品时,我想要这个自定义错误页面。

我创建了自己的自定义错误页面 NotFound.aspx

该页面的内部内容是:

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Simple.Master" 
Inherits="System.Web.Mvc.ViewPage<System.Web.Mvc.HandleErrorInfo>" %> 
<asp:Content ID="errorTitle" ContentPlaceHolderID="TitleContent" runat="server"> 
Error 
</asp:Content> 
<asp:Content ID="errorContent" ContentPlaceHolderID="MainContent" runat="server"> 
<h2> 
Sorry, you requested a product that doesn't exist. Make sure you
requested a valid ProductID 
</h2> 
</asp:Content>

然后将HandleError过滤器应用到我的 ActionMethod:Details为:

[HandleError(View="NotFound")] 
public ActionResult Details(int id) {...

问题是,始终 Views/Shared/Error.aspx调用默认视图:而不是新的自定义错误页面。有什么想法吗 ?

4

4 回答 4

3

试试这个(但我不确定这个代码在 MVC 中的工作)。将此代码粘贴到 web.config 文件 brlow system.web 的配置部分。

 <customErrors mode="On" defaultRedirect="ErrorPage.aspx">
    </customErrors>
    <compilation debug="true" targetFramework="4.0">
于 2013-08-12T08:39:58.260 回答
2

尝试使用 Web 配置文件中的自定义错误标记,这可能对您有所帮助。

这是示例

<system.web>
   <--- other required may be used here--->     

    <customErrors mode="On" defaultRedirect="ErrorPage.aspx"></customErrors>
  </system.web>
于 2013-08-14T04:48:51.157 回答
1

解决方案是我的ProductController班级还需要将order属性设置为:

[HandleError(Order=2)] 
public class ProductController : Controller { ... }

这意味着什么:Order 值为 2 将确保仅在没有可用的更高阶的 HandleError 过滤器时应用控制器范围的过滤器。

这非常有效。我的 web.config 设置是: <customErrors mode="On" />.

就是这个。defaultRedirect根本不需要。

注意:HandleError最初的过滤器没有 order属性。

[HandleError] 
public class ProductController : Controller { ... }

当您应用不带参数的 HandleError 过滤器时,您指定由过滤器涵盖的方法引发的任何异常都将导致Views/Shared/Error.aspx视图被使用。

于 2013-09-02T04:10:26.880 回答
0

确保您在同一个控制器中的“未找到”操作和“详细”操作。否则,您应该指定控制器名称,或者将 notfound.aspx 放在共享文件夹下

于 2013-08-12T08:55:01.747 回答