• ASP.net MVC3里的HandleErrorAttribute


    在MVC3里使用HandleErrorAttribte类,有2种方式可以使用它,一是在类或者方法上直接使用HandleError属性来定义:

    // 在这里声明
    [HandleError]
    public class HomeController : Controller
    {
    // 或者在这里声明
    // [HandleError]
    public ActionResult Index()
    {
    return View();
    }
    }


    另外一种方式是使用MVC3的Global Filters功能来注册,默认新建MVC项目在Global.asax文件里就已经有了,代码如下:

    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
    filters.Add(new HandleErrorAttribute());
    }

    public static void RegisterRoutes(RouteCollection routes)
    {
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
    );

    }

    protected void Application_Start()
    {
    AreaRegistration.RegisterAllAreas();

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);
    }


    代码段里的filters.Add(new HandleErrorAttribute());设置是说整个程序所有的Controller都使用这个HandleErrorAttribute来处理错误。

    注意:HandleErrorAttribute只处理500系列错误,所以404错误需要另外单独处理,稍后会提到。


    下一步,我们要做的是开启web.config根目录里的customErrors(不是views目录下的那个web.config哦),代码如下:

    <customerrors mode="On" defaultredirect="~/Error/HttpError">
    <error redirect="~/Error/NotFound" statuscode="404" />
    </customerrors>

    defaultredirect是设置为所有错误页面转向的错误页面地址,而里面的error元素可以单独定义不同的错误页面转向地址,上面的error行就是定义404所对应的页面地址。

    最后一件事,就是定义我们所需要的错误页面的ErrorController:

    public class ErrorController : BaseController
    {
    //
    // GET: /Error/
    public ActionResult HttpError()
    {
    return View("Error");
    }
    public ActionResult NotFound()
    {
    return View();
    }
    public ActionResult Index()
    {
    return RedirectToAction("Index", "Home");
    }
    }


    默认Error的view是/views/shared/Error.cshtml文件,我们来改写一下这个view的代码,代码如下:

    @model System.Web.Mvc.HandleErrorInfo
    @{
    ViewBag.Title = "General Site Error";
    }

    <h2>A General Error Has Occurred</h2>

    @if (Model != null)
    {
    <p>@Model.Exception.GetType().Name<br />
    thrown in @Model.ControllerName @Model.ActionName</p>
    <p>Error Details:</p>
    <p>@Model.Exception.Message</p>
    }


    你也可以通过传递参数来重写GlobalFilter里的HandleErrorAttribte注册,单独声明一个特定的Exception,并且带有Order参数,当然也可以连续声明多个,这样就会多次处理。

    filters.Add(new HandleErrorAttribute
    {
    ExceptionType = typeof(YourExceptionHere),
    // DbError.cshtml是一个Shared目录下的view.
    View = "DbError",
    Order = 2
    });
     
     
    转自:http://www.cnblogs.com/TomXu/archive/2011/12/15/2285432.html
  • 相关阅读:
    mysql将一个表的数据 重复复制多份到表中
    PHP中将指定文本内容导入到word中
    系统安全-SElinux
    通过身份证号码提取年龄,性别
    MySQL-获取某天的数据
    mysql-介绍、MySQL部署、数据类型、存储引擎
    监控系统-ELK
    监控系统-Grafana
    监控系统-zabbix
    监控系统-openfalcon
  • 原文地址:https://www.cnblogs.com/aaronguo/p/4730252.html
Copyright © 2020-2023  润新知