繁体   English   中英

ASP.NET MVC 5如何才能专门捕获所有System.NullReferenceExceptions并重定向到视图,这样我的程序就不会崩溃?

[英]ASP.NET MVC 5 How can I catch specifically all System.NullReferenceExceptions and redirect to a view, so my program doesnt crash?

我正在寻找一种方法来处理asp.net应用程序中的所有空引用异常,并在遇到异常时进行处理,例如重定向到错误页面。 我试过在global.asax中放一些东西,但是似乎没有用。 所以我的问题是,例如,如果我有这样的代码,当没有参数时会抛出异常:

  public ActionResult GeneratePDFforSignature(int? id)
    {

        Signature signature = db.SignatureDatabase.Find(id);
        return View();
    }

如何在整个范围内捕获异常应用程序并阻止应用程序崩溃。 我已经阅读了一些有关此问题的内容,并向我的global.asax添加了一些代码,但是它不处理null引用异常。

这就是我添加到Global.asax中的内容。 我在另一个线程( ASP.NET MVC 5错误处理 )中找到它:

    protected void Application_Error()
    {
        HttpContext httpContext = HttpContext.Current;
        if (httpContext != null)
        {
            RequestContext requestContext = ((MvcHandler)httpContext.CurrentHandler).RequestContext;
            /* when the request is ajax the system can automatically handle a mistake with a JSON response. then overwrites the default response */
            if (requestContext.HttpContext.Request.IsAjaxRequest())
            {
                httpContext.Response.Clear();
                string controllerName = requestContext.RouteData.GetRequiredString("controller");
                IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory();
                IController controller = factory.CreateController(requestContext, controllerName);
                ControllerContext controllerContext = new ControllerContext(requestContext, (ControllerBase)controller);

                JsonResult jsonResult = new JsonResult();
                jsonResult.Data = new { success = false, serverError = "500" };
                jsonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                jsonResult.ExecuteResult(controllerContext);
                httpContext.Response.End();
            }
            else
            {
                httpContext.Response.Redirect(Server.MapPath("~/Shared/Error.cshtml"));
            }
        }

如果可能的话,如何捕获所有空引用异常? 我知道我可以通过添加一个

        if (id == null){//code}

但是我的程序很大,我希望找到一个能够捕获所有内容的解决方案,因此我不必复制和粘贴代码段即可捕获不同控制器之间的异常400次。 如何捕获所有空引用异常并重定向到ASP.NET MVC 5中的错误页面?

建议不要通过修改路由表来阻止所有空引用异常。

我猜你有一条看起来像这样的路线:

{action}/{id?}

问题是id显然不是真正可选的。 因此,路线应改为以下形式(无问号):

{action}/{id}

然后,您将需要一条附加路由来捕获与任何路由定义都不匹配的任何HTTP请求(包括不带ID的GeneratePDFforSignature)。 您可以将其附加到路由定义的末尾,例如(如下所示):

routes.MapRoute( 
  name= "CatchAll", 
  url="{*any}", 
  defaults = new {controller = "Error", action = "Handler"} 
)

您的控制器名称和操作名称可能有所不同,但是您明白了。

        //use this

        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Web;
        using System.Web.Mvc;
        using System.Web.Routing;

        namespace nullReference_Exception.Models
        {
            public class CustomException : FilterAttribute, IExceptionFilter
            {
                public void OnException(ExceptionContext filterContext)
                {
                    if (filterContext.Exception.InnerException == null)
                    {
                        if (!filterContext.ExceptionHandled && filterContext.Exception is Exception)
                        {
                            filterContext.Result = new RedirectToRouteResult(
                                           new RouteValueDictionary 
                                           {
                                               { "action", "Error" },
                                               { "controller", "Home" }
                                           });
                            filterContext.ExceptionHandled = true;
                        }
                    }

                }
            }
        }


    //at controller

    using nullReference_Exception.Models;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;

    namespace nullReference_Exception.Controllers
    {
        [CustomException]  //on every controller 
        public class HomeController : Controller
        {
            public ActionResult Index()
            {
                LoginViewModel aLog=null;
                var a=aLog.Email;
                return View();
            }

//you don't need to declare this on every controller

            public ActionResult Error()
            {
                return View();
            }
            public ActionResult About()
            {
                ViewBag.Message = "Your application description page.";

                return View();
            }

            public ActionResult Contact()
            {
                ViewBag.Message = "Your contact page.";

                return View();
            }
        }
    }

    // now make a error action and view
//read comment carefully

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM