zoukankan      html  css  js  c++  java
  • 获取MVC中Controller下的Action参数异常

    我现在做的一个项目有一个这样的需求,

    比如有一个页面需要一个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 发现了他的 NameActionDescriptor,这个好像有点搞头。

    通过一些其他大神的博客 我确定只要我的异常的 TargetSite.ReflectedType.NameActionDescriptor,我就认定他是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();
                }
            }

    以上就是我的做法,如果大家发现我的问题或有什么好的方法欢迎告诉我一下哦!

  • 相关阅读:
    学习进度(2)
    模拟退火 [JSOI2004]平衡点 / 吊打XXX
    快读快写 O3 优化
    卡特兰数(Catalan)公式、证明、代码、典例
    树状数组 :单点修改,区间查询
    倍增 [模板]最近公共祖先LCA
    对测 【模拟】
    对测 【离线DP+二分】
    模拟退火 (骗分算法)
    基础数论入门
  • 原文地址:https://www.cnblogs.com/T-FQlin/p/6434838.html
Copyright © 2011-2022 走看看