簡體   English   中英

從tempdata視圖中的Asp.Net Mvc顯示異常

[英]Asp.Net Mvc Display exception in View from tempdata

我正在處理基本控制器中的錯誤。 我需要在剃刀視圖中顯示存儲在tempdata中的錯誤,異常類型。 我怎樣才能做到這一點?

基本控制器代碼

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

剃刀查看代碼

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

嘗試進行通用異常屬性處理,並將其注冊為全局過濾器。 喜歡,

通用異常處理屬性:

    /// <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;
        }
    }

和錯誤/ _Error視圖

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

我同意您永遠都不應向視圖公開異常,但如果確實需要,請嘗試使用自定義屬性。

 public class CustomExceptionAttribute : System.Web.Mvc.HandleErrorAttribute
    {
        public override void OnException(System.Web.Mvc.ExceptionContext filterContext)
        {
            if (!filterContext.ExceptionHandled)
            {
                filterContext.Controller.TempData.Add("Exception", filterContext.Exception);
                filterContext.ExceptionHandled = true;
            }
        }
    }

    public class MyController : System.Web.Mvc.Controller
    {
        [CustomException]
        public ActionResult Test()
        {
            throw new InvalidOperationException();
        }
    }

如果在基本控制器中重寫OnException方法,則每個操作都將獲得一個放在臨時數據中的Exception對象。 這也許是理想的行為,但是通過屬性可以有選擇地啟用此功能。

我強烈建議不要在任何面向公眾的應用程序中顯示任何詳細的異常信息,因為這最終可能會導致安全問題。 但是,如果這是具有受控訪問權限的Intranet應用程序,或者如果您確實要顯示異常詳細信息,請創建一個DisplayTemplate並按以下方式使用它:

<div>
Exception Details
@Html.Display(TempData["Exception"])
</div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM