当前位置: 移动技术网 > IT编程>开发语言>.net > ASP.NET MVC错误处理的对应解决方法

ASP.NET MVC错误处理的对应解决方法

2018年04月10日  | 移动技术网IT编程  | 我要评论

乔雯婧,龙口教育城域网,标致308三厢

asp.net mvc的错误处理应考虑到这几个方面:模型绑定期间发生的错误,未能路由到指定操作,针对控制器的错误处理。使用配置文件可以帮助我们处理异常,但是不够灵活和全面;使用handleerrorattribute、自定义错误过滤器或重写控制器onexception方法只能解决针对控制器的错误,无法解决模型绑定期间发生的错误,也无法处理404错误,即使将错误过滤器注册为全局过滤器也是如此。有时候需要多种方法配合使用。

在捕获错误的地方,可以将有用的信息记录下来,便于我们查出引起问题的原因和纠正错误。

1启用自定义错误

使用这种方式一定要注意将defaultredirect设置为指定的错误页面,防止黑客探测各种错误情形进而发现系统的额漏洞。

<system.web>
 <customerrors mode="on" defaultredirect="/error/error2">
  <error statuscode="404" redirect="/error/error1" />
 </customerrors>
 <!--其他配置-->
</system.web>

mode:处理模式,有三种处理模式

  • on,启用自定义处理功能,当错误发生时显示自定义错误页
  • off,关闭自定义错误处理功能,当错误发生时显示默认的错误页。
  • remoteonly,启用自定义错误处理功能,但只针对来自远程机器的请求有效。

defaultredirect:发生错误时,显示指定错误页。

<error>:根据状态码显示指定的错误页。mode必须为on或remoteonly模式,否则不会起作用。

注意:不论defaultredirect和redirect都配置为指定的路径,例如上述配置中控制器error,控制器操作为error1和error2,相应地错误页为error1.cshtml和error2.cshtml。

2针对控制器的错误处理

2.1使用handleerrorattribute修饰控制器或操作。

[attributeusage(attributetargets.class | attributetargets.method, inherited = true, allowmultiple = true)]
public class handleerrorattribute : filterattribute, iexceptionfilter
{
    //获取或设置异常的类型。
    public type exceptiontype { get; set; } 
    //获取或设置用于显示异常信息的母版视图
    public string master { get; set; }
    //获取此特性的唯一标识符。
    public override object typeid { get; }
    //获取或设置用于显示异常信息的页视图。
    public string view { get; set; }
    //在发生异常时调用。 
    //filtercontext:操作筛选器上下文
    public virtual void onexception(exceptioncontext filtercontext);
}

例:

当发生keynotfoundexception类型的异常时,显示keynotfind视图

[handleerror(exceptiontype=typeof(keynotfoundexception),view="keynotfound")]
public actionresult index()
{
  ......
}

还可以使用自定义的错误过滤器,并将其应用到控制器或操作上。

例:

public class customhandleerror : handleerrorattribute
  {
    public override void onexception(exceptioncontext filtercontext)
    {
      if (filtercontext==null)
        base.onexception(filtercontext);

      //记录日志
      logerror(filtercontext.exception);

      //判断是否启用了自定义错误
      if (filtercontext.httpcontext.iscustomerrorenabled)
      {
        //将错误设置为已处理
        filtercontext.exceptionhandled = true;
        base.onexception(filtercontext);
      }
    }
  }

可以设置全局过滤器,这样对每一个控制器都起作用。

app_start文件夹下filterconfig.cs文件中设置全局错误过滤器,过滤器会按照他们注册的顺序执行。但可以通过order属性指定执行顺序。

例:

public class filterconfig
{
    public static void registerglobalfilters(globalfiltercollection filters)
    {
      filters.add(new handleerrorattribute 
      {
        exceptiontype = typeof(keynotfoundexception),
        view = "keynotfound",
        order = 2
      });
      filters.add(new handleerrorattribute(),1);
    }
}

将自定义错误过滤器设置为全局过滤器:

在app_start文件夹下filterconfig.cs文件中

例:

public class filterconfig
  {
    public static void registerglobalfilters(globalfiltercollection filters)
    {
      
       //其他过滤器

       filters.add(new customhandleerror());
     }
   }

2.2重写控制器onexception方法

注意将错误设置为已处理,不然错误继续抛出,但如果设置了全局错误过滤器,那么即使不标记为已处理,也不要紧,因为错误最终会被全局过滤器捕获并处理。

例:

public class homecontroller : controller
 {

    //其他控制器操作

    protected override void onexception(exceptioncontext filtercontext)
    {
      if (filtercontext==null)
        base.onexception(filtercontext);

      //记录日志
      logerror(filtercontext.exception);

      //判断是否启用了自定义错误
      if (filtercontext.httpcontext.iscustomerrorenabled)
      {
        //将错误设置为已处理
        filtercontext.exceptionhandled = true;
        //显示错误页
      this.view("error").executeresult(this.controllercontext);
      }
    }
}

或者创建控制器基类

public class basecontroller : controller
  {
    protected override void onexception(exceptioncontext filtercontext)
    {
      //错误日志记录
    }
  }

3全局错误处理

针对模型绑定或路由等过程中抛出的异常我们只能使用全局错误处理策略。

3.1 global.asax中添加处理异常的代码

例:

 public class mvcapplication : system.web.httpapplication
  {
    protected void application_start()
    {
      arearegistration.registerallareas();
      filterconfig.registerglobalfilters(globalfilters.filters);
      routeconfig.registerroutes(routetable.routes);
      bundleconfig.registerbundles(bundletable.bundles);
    }

    protected void application_error(object sender, eventargs e)
    {
      var exception = server.getlasterror();
      if (exception == null)
      {
        return;
      }

      //异常发生记录日志或发送邮件

      //清除异常
      server.clearerror();

      //重定向
      response.redirect("home/index");
    }
  }

3.2捕获未匹配的路由

在路由注册列表最底端注册路由。

public class routeconfig
  {
    public static void registerroutes(routecollection routes)
    {
      //其他配置
      routes.maproute(
        name: "matchall",
        url: "{*anyurl}",
        defaults: new { controller = "error",action ="missing" }
        );
     }
   }

定义error控制器及missing操作

public class errorcontroller : controller
  {
    // get: error
    public actionresult missing()
    {
      httpcontext.response.statuscode = 404;
      //禁用iis7默认的错误页,这样才能展示我们指定都的视图
      httpcontext.response.tryskipiiscustomerrors = true;

      //也可以在此处记录日志信息

      //要展示的信息
      var model = ......
      return view(model);
    }
   }

需要注意的是,这种方式不一定能处理所有未匹配的情形。

例如:http://localhost/mvcpointapp/home/index1,这个url请求说我home是存在,但是index1操作不存在,上面配置matchall路由无法匹配这个url。

可以匹配的情形如:http://localhost/mvcpointapp/v1/home/index/1,这个url能被上面配置的matchall路由匹配,所以可以显示missing视图。

4实践

4.1使用handleerrorattribute注意要对<system.web>的<customerrors>节进行设置 。

例如:

控制器为

public class homecontroller : controller
  {
    [handleerror(exceptiontype = typeof(keynotfoundexception), view = "error")]
    public actionresult index()
    {
      throw new keynotfoundexception();
      return view();
    }

    //其他控制操作

   }

<system.web>的<customerrors>节

<customerrors mode="on" defaultredirect="error/error2"></customerrors>

error.cshtml文件位于views文件夹下的子文件夹shared文件夹下

浏览器中输入:http://localhost/mvcpointapp/

结果可以正常显示error.cshtml页面,同时注意到虽然在customerrors 配置节中指定了defaultredirect,但还是跳转到error.cshtml页面。

将<customerrors>的mode设置为off,则显示经典错误页。

4.2 application_error

代码如3.1节所示,控制器如4.1所示,<system.web>的<customerrors>节为<customerrors mode="on" defaultredirect="error/error2"></customerrors>

输入:http://localhost/mvcpointapp/home/index,断点调试,发现错误被handleerror拦截,global.asax的application_error方法没有执行。而当输入:http://localhost/mvcpointapp/home/indexr,application_error执行了。

关闭<customerrors>配置节,而不注掉控制器上的handleerrorattribute特性,输入:http://localhost/mvcpointapp/home/index,发现application_error执行了。

通过上述实践,充分证明handleerrorattribute会拦截控制器内抛出的异常,而无法拦截无法找到资源这种异常。

4.3策略

一种常用的拦截错误信息、记录错误日志与显示自定义错误页的策略为:

1)首先配置<system.web>的<customerrors>节,注意务必设置defaultredirect;并且定义错误控制器及相应的操作和视图。

2)定义基类控制器或自定义错误过滤器,记录异常。对于自定义错误过滤器的情形一般将其注册为全局过滤器。

3)在global.asax中添加application_error方法拦截意想不到的异常并记录异常。

参考:

1.jess chadwick/todd snyder/hrusikesh panda,徐雷/徐扬

译。asp.net mvc4 web编程

2.jon galloway/phil haack/brad wilson/k. scott allen,孙远帅/邹权译  asp.net mvc4 高级编程(第四版)

3.黄保翕,asp.net mvc4开发指南

4.蒋金楠,asp.net mvc4框架揭秘

5.https://www.asp.net/mvc

6.dino esposito著,潘丽臣译,asp.net mvc5编程实战

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网