Razor中进行错误处理

Razor中进行错误处理

本文介绍了我们如何在ASP.NET MVC3 Razor中进行错误处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是MVC3的新手。我为一些CRUD操作做了一个MCV3应用程序。现在我想在MVC3中进行错误处理。我在一篇文章中看到过关于错误处理。请简要介绍一下错误处理MVC?我们是否需要创建任何自定义类来处理错误处理?

I am a newbie to MVC3 .I have done a MCV3 application for some CRUD operation.Now I want to do the Error Handling in MVC3.I have seen in an article Article about Error Handling.Can you please briefly about Error handling in MVC? Do we need to create any custom class to handle Error Handling?

推荐答案

using System.Web;
using System.Web.Mvc;

namespace App.Web
{
  public class CustomHandleErrorAttribute : HandleErrorAttribute
  {
    public CustomHandleErrorAttribute()
    {
    }

    public override void OnException(ExceptionContext filterContext)
    {
      if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled)
      {
        return;
      }

      if (new HttpException(null, filterContext.Exception).GetHttpCode() != 500)
      {
        return;
      }

      if (!ExceptionType.IsInstanceOfType(filterContext.Exception))
      {
        return;
      }

      // if the request is AJAX return JSON else view.
      if (filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
      {
        filterContext.Result = new JsonResult
        {
          JsonRequestBehavior = JsonRequestBehavior.AllowGet,
          Data = new
          {
            error = true,
            message = filterContext.Exception.Message
          }
        };
      }
      else
      {
        var controllerName = (string)filterContext.RouteData.Values["controller"];
        var actionName = (string)filterContext.RouteData.Values["action"];
        var model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);

        filterContext.Result = new ViewResult
        {
          ViewName = View,
          MasterName = Master,
          ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
          TempData = filterContext.Controller.TempData
        };
      }
      filterContext.ExceptionHandled = true;
      filterContext.HttpContext.Response.Clear();
      filterContext.HttpContext.Response.StatusCode = 500;

      filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
    }
  }
}



然后将以下代码放入Global.asax.cs


and then put the below code in Global.asax.cs

protected void Application_Error(object sender, EventArgs e)
       {
           var httpContext = ((MvcApplication)sender).Context;
           var currentController = " ";
           var currentAction = " ";
           var currentRouteData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext));

           if (currentRouteData != null)
           {
               if (currentRouteData.Values["controller"] != null && !String.IsNullOrEmpty(currentRouteData.Values["controller"].ToString()))
               {
                   currentController = currentRouteData.Values["controller"].ToString();
               }

               if (currentRouteData.Values["action"] != null && !String.IsNullOrEmpty(currentRouteData.Values["action"].ToString()))
               {
                   currentAction = currentRouteData.Values["action"].ToString();
               }
           }

           var ex = Server.GetLastError();
           var controller = new ErrorController();
           var routeData = new RouteData();
           var action = "Index";

           if (ex is HttpException)
           {
               var httpEx = ex as HttpException;

               switch (httpEx.GetHttpCode())
               {
                   case 404:
                       action = "NotFound";
                       break;

                   case 401:
                       action = "AccessDenied";
                       break;
               }
           }

           httpContext.ClearError();
           httpContext.Response.Clear();
           httpContext.Response.StatusCode = ex is HttpException ? ((HttpException)ex).GetHttpCode() : 500;
           httpContext.Response.TrySkipIisCustomErrors = true;

           routeData.Values["controller"] = "Error";
           routeData.Values["action"] = action;

           controller.ViewData.Model = new HandleErrorInfo(ex, currentController, currentAction);
           ((IController)controller).Execute(new RequestContext(new HttpContextWrapper(httpContext), routeData));
       }





然后创建一个控制器来捕获如下错误



and then Create a Controller for Catching the error like below

public class ErrorController : Controller
    {
        public ActionResult Index()
        {
            var error = ViewData.Model;
            return View(error);
        }

        public ActionResult NotFound()
        {
            var error = ViewData.Model;
            return View(error);
        }

        public ActionResult AccessDenied()
        {
            var error = ViewData.Model;
            return View(error);
        }
    }



然后创建3个视图,例如error.cshtml,NotFound.cshtml,AccessDenied.cshtml并粘贴以下标记每个视图或为其创建局部视图并调用每个视图。这三个视图返回相同的模型。

例如


and then Create 3 views such as error.cshtml,NotFound.cshtml,AccessDenied.cshtml and paste the below mark up in each view or create a partial view for that and call in to each view. These three views are return the same model.
for example

<div><b>Controller:</b> @Model.ControllerName</div>
<div><b>Action Name :</b> @Model.ActionName</div>
<div><b>Exception:</b> @Model.Exception.Message</div>
<a href="#" style="color:Blue" id="clickMore">Click here to see more details</a>
<div id="moreDetails">
<div><b>Stack Trace:</b> @Model.Exception.StackTrace</div>
<div><b>Inner Exception:</b> @Model.Exception.InnerException</div>
</div>


这篇关于我们如何在ASP.NET MVC3 Razor中进行错误处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 21:45