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();
                }
            }

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

  • 相关阅读:
    LeetCode 1032. Stream of Characters
    LeetCode 872. Leaf-Similar Trees
    LeetCode 715. Range Module
    LeetCode 353. Design Snake Game
    LeetCode 509. Fibonacci Number
    LeetCode 632. Smallest Range Covering Elements from K Lists
    LeetCode 963. Minimum Area Rectangle II
    LeetCode 939. Minimum Area Rectangle
    LeetCode 727. Minimum Window Subsequence
    LeetCode 844. Backspace String Compare
  • 原文地址:https://www.cnblogs.com/T-FQlin/p/6434838.html
Copyright © 2011-2022 走看看