c# - ASP.NET MVC3中不同区域的自定义错误页面

标签 c# asp.net-mvc-3 error-handling

我已经在我的网站上设置了自定义错误页面,使用

<customErrors mode="RemoteOnly" defaultRedirect="~/Error">
  <error statusCode="500" redirect="~/Error/InternalError"/>
  <error statusCode="404" redirect="~/Error/FileNotFound"/>
  <error statusCode="403" redirect="~/Error/AccessDenied"/>
</customErrors>

但是网站上还有另一个区域 Suppliers,当供应商区域发生错误时,重定向会转到 Suppliers/Error/_。由于我这里没有任何错误页面,该站点似乎挂起,从不显示错误页面。如何解决此问题而不必将错误页面复制到供应商区域?

最佳答案

据我对 MVC 的了解,您的 URL 构成默认情况下是:

域/ Controller / Action /id

如果您有一个“错误” Controller 。在您的逻辑中,您测试请求是否来自需要重定向到“供应商”错误页面的网站用户

 [HandleError]
    public ActionResult Index()
    {
        // Test to see if you need to go to the SuppliersController
        if (this.User.IsInRole("supplier"))
        {
            return Redirect("/Suppliers/Error");
        }
        else
        {
            return View(); // This returns the "Error" View from the shared folder
        }
    }

重定向到供应商 Controller 上的错误处理操作,它将返回正确的 View 。

public class SuppliersController : Controller
{
    //
    // GET: /Suppliers/

    public ActionResult Error()
    {
        return View("Error","SomeMasterPage"); // No "Error" view in Suppliers View folder, so it uses the one in shared folder
    }

}

您还可以在供应商错误操作中使用 [Authorize] 属性来确保用户已登录。

通过这种方式,您将获得所需的 /Suppliers/Error URL,并可以使用 SuppliersController 操作来指定所需的 View 、模型和主/布局页面。

另请参阅对类似问题的非常全面的回复:

Best 404 example I can find for mvc

关于c# - ASP.NET MVC3中不同区域的自定义错误页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7243302/

相关文章:

ASP.net - 如何实现具有常量值、算术和字符串操作的 CSS

function - Try/Catch语句似乎不起作用

c# - ASP.NET MVC SqlException不会重定向到错误页面

c# - .Net MVC 中的 "Model"

c# - SQL查询执行难度

c# - 如何获取我试图在 IModelBinder 中绑定(bind)的参数的属性?

c# - 使用 Fluent NHibernate 编写 MySql 数据库包装器

c# - asp.net mvc url中的双引号

c# - 在 C# 中使用位掩码

c# - 如何使用c#获取两个日期之间的天数和夜数