我现在做的一个项目有一个这样的需求,
比如有一个页面需要一个Guid类型的参数:
public ActionResult Index(Guid id) { //doing something ... return View(); }
当在url地址栏中输入非Guid的参数,因为无法转为Guid类型的数据,这个时候会抛出异常,可是在这个时候要进入404页面.不要进入错误页面
在这个前提下,我首先获取到这个异常,在Global 文件里的方法:
protected void Application_Error(object sender, EventArgs e) {}
中获取异常
Exception ex = Server.GetLastError().GetBaseException();
因为不是所有异常都要进入404,那现在我就需要判断一下我获取到的异常是action的参数异常
我研究了一下抛出的异常,首先是一个 ArgumentException 可是只知道这些还不行,再往里找发现了 TargetSite.ReflectedType 发现了他的 Name 为 ActionDescriptor,这个好像有点搞头。
通过一些其他大神的博客 我确定只要我的异常的 TargetSite.ReflectedType.Name 为 ActionDescriptor,我就认定他是Action参数异常,接下来贴一下我的代码:
protected void Application_Error(object sender, EventArgs e) { Exception ex = Server.GetLastError().GetBaseException(); if ((ex is HttpException && ((HttpException)ex).GetHttpCode() == 404)||(ex is ArgumentException&&((ArgumentException)ex).TargetSite.ReflectedType?.Name== "ActionDescriptor")) { //Give you 404.html...//把已经处理的异常清理掉 Server.ClearError(); } }
以上就是我的做法,如果大家发现我的问题或有什么好的方法欢迎告诉我一下哦!