从TempData的在查看Asp.Net的mvc显示异常 [英] Asp.Net Mvc Display exception in View from tempdata

查看:163
本文介绍了从TempData的在查看Asp.Net的mvc显示异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在基地控制器处理错误。我需要在剃刀视图以显示存储在TempData的错误,异常类型。我该怎么做?

基本控制器code

 保护覆盖无效onException的(ExceptionContext filterContext)
        {
            //如果(filterContext.ExceptionHandled)
            //返回;            //我们要求知道错在哪里
            filterContext.Controller.TempData [异常] = filterContext.Exception.Message;            //重定向到错误处理程序
            filterContext.Result =新RedirectToRouteResult(新RouteValueDictionary(
                新{控制器=错误,行动=索引}));            //停止运行任何其他异常处理程序
            filterContext.ExceptionHandled = TRUE;            //清除任何东西已经在响应
            filterContext.HttpContext.Response.Clear();
        }

的Razor视图code

 < D​​IV>
            这是错误说明
            @ Html.Raw(Html.En code(TempData的[异常]))
        < / DIV>


解决方案

尽量让常见的例外处理的属性并将其注册为全局过滤器。就像,

常见异常处理属性:

  ///<总结>
    ///这个动作过滤器会处理有HTTP响应code 500错误。
    ///由于阿贾克斯不处理此错误。
    ///< /总结>
    [AttributeUsage(AttributeTargets.Class)
    公共密封类HandleErrorAttribute:FilterAttribute,个IExceptionFilter
    {
        私有类型exceptionType = typeof运算(例外);        私人常量字符串默认视图=错误;        私人常量字符串DefaultAjaxView =_Error;        公共类型ExceptionType
        {
            得到
            {
                返回this.exceptionType;
            }            组
            {
                如果(价值== NULL)
                {
                    抛出新的ArgumentNullException(值);
                }                this.exceptionType =价值;
            }
        }        公共字符串查看{搞定;组; }        公共字符串主{搞定;组; }        公共无效onException的(ExceptionContext filterContext)
        {
            如果(filterContext == NULL)
            {
                抛出新的ArgumentNullException(filterContext);
            }            如果(filterContext.IsChildAction&安培;!及(filterContext.ExceptionHandled&安培;!&安培; filterContext.HttpContext.IsCustomErrorEnabled))
            {
                异常的InnerException = filterContext.Exception;                //添加内部服务器错误(500 HTTP状态code)
                如果((新HttpException(NULL,的InnerException).GetHttp code()== 500)及和放大器; this.ExceptionType.IsInstanceOfType(的InnerException))
                {
                    VAR controllerName =(字符串)filterContext.RouteData.Values​​ [控制器];
                    VAR actionName =(字符串)filterContext.RouteData.Values​​ [行动];
                    VAR模型=新HandleErrorInfo(filterContext.Exception,controllerName,actionName);                    //为Ajax请求检查
                    如果(filterContext.HttpContext.Request.IsAjaxRequest())
                    {
                        VAR的结果=新PartialViewResult
                        {
                            VIEWNAME = string.IsNullOrEmpty(this.View)? DefaultAjaxView:this.View,
                            ViewData的=新的ViewDataDictionary< HandleErrorInfo>(模型),
                            TempData的= filterContext.Controller.TempData
                        };
                        filterContext.Result =结果;
                    }
                    其他
                    {
                        VAR的结果= this.CreateActionResult(filterContext,模型);
                        filterContext.Result =结果;
                    }                    filterContext.ExceptionHandled = TRUE;
                }
            }
        }        私人的ActionResult CreateActionResult(ExceptionContext filterContext,HandleErrorInfo模型)
        {
            VAR的结果=新的ViewResult
            {
                VIEWNAME = string.IsNullOrEmpty(this.View)?默认视图:this.View,
                MasterName = this.Master,
                ViewData的=新的ViewDataDictionary< HandleErrorInfo>(模型),
                TempData的= filterContext.Controller.TempData,
            };            result.TempData [异常] = filterContext.Exception;            返回结果;
        }
    }

和错误/ _Error视图

  @model HandleErrorInfo
< D​​IV>
    这是错误说明
    @TempData [异常]
 < / DIV>

I am handling error in Base controller. I need to display the error stored in tempdata, Exception type in a razor view. How can I do that?

Base Controller code

 protected override void OnException(ExceptionContext filterContext)
        {
            // if (filterContext.ExceptionHandled)
            //   return;

            //Let the request know what went wrong
            filterContext.Controller.TempData["Exception"] = filterContext.Exception.Message;

            //redirect to error handler
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(
                new { controller = "Error", action = "Index" }));

            // Stop any other exception handlers from running
            filterContext.ExceptionHandled = true;

            // CLear out anything already in the response
            filterContext.HttpContext.Response.Clear();
        }

Razor View Code

        <div>
            This is the error Description         
            @Html.Raw(Html.Encode(TempData["Exception"]))
        </div>

解决方案

Try to make common exception attribute handling and register it as global filters. Like,

Common Exception Handling attribute :

    /// <summary>
    /// This action filter will handle the errors which has http response code 500. 
    /// As Ajax is not handling this error.
    /// </summary>
    [AttributeUsage(AttributeTargets.Class)]
    public sealed class HandleErrorAttribute : FilterAttribute, IExceptionFilter
    {
        private Type exceptionType = typeof(Exception);

        private const string DefaultView = "Error";

        private const string DefaultAjaxView = "_Error";

        public Type ExceptionType
        {
            get
            {
                return this.exceptionType;
            }

            set
            {
                if (value == null)
                {
                    throw new ArgumentNullException("value");
                }

                this.exceptionType = value;
            }
        }

        public string View { get; set; }

        public string Master { get; set; }

        public void OnException(ExceptionContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            if (!filterContext.IsChildAction && (!filterContext.ExceptionHandled && filterContext.HttpContext.IsCustomErrorEnabled))
            {
                Exception innerException = filterContext.Exception;

                // adding the internal server error (500 status http code)
                if ((new HttpException(null, innerException).GetHttpCode() == 500) && this.ExceptionType.IsInstanceOfType(innerException))
                {
                    var controllerName = (string)filterContext.RouteData.Values["controller"];
                    var actionName = (string)filterContext.RouteData.Values["action"];
                    var model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);

                    // checking for Ajax request
                    if (filterContext.HttpContext.Request.IsAjaxRequest())
                    {
                        var result = new PartialViewResult
                        {
                            ViewName = string.IsNullOrEmpty(this.View) ? DefaultAjaxView : this.View,
                            ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
                            TempData = filterContext.Controller.TempData
                        };
                        filterContext.Result = result;
                    }
                    else
                    {
                        var result = this.CreateActionResult(filterContext, model);
                        filterContext.Result = result;
                    }

                    filterContext.ExceptionHandled = true;
                }
            }
        }

        private ActionResult CreateActionResult(ExceptionContext filterContext, HandleErrorInfo model)
        {
            var result = new ViewResult
            {
                ViewName = string.IsNullOrEmpty(this.View) ? DefaultView : this.View,
                MasterName = this.Master,
                ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
                TempData = filterContext.Controller.TempData,
            };

            result.TempData["Exception"] = filterContext.Exception;

            return result;
        }
    }

And Error/_Error view

@model HandleErrorInfo
<div>
    This is the error Description
    @TempData["Exception"]
 </div>

这篇关于从TempData的在查看Asp.Net的mvc显示异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆