CustomExceptionAttribute.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Linq;
  5. using System.Web;
  6. using System.Web.Mvc;
  7. using System.Web.Mvc.Properties;
  8. namespace EMIS.Web.Controls.Filters
  9. {
  10. [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
  11. public class CustomExceptionAttribute : HandleErrorAttribute, IExceptionFilter
  12. {
  13. private Type _exceptionType = typeof(Exception);
  14. private string _master;
  15. private readonly object _typeId = new object();
  16. private string _view;
  17. private const string DefaultView = "Error";
  18. public override void OnException(ExceptionContext filterContext)
  19. {
  20. if (filterContext == null)
  21. {
  22. throw new ArgumentNullException("filterContext");
  23. }
  24. if (!filterContext.IsChildAction && (!filterContext.ExceptionHandled && filterContext.HttpContext.IsCustomErrorEnabled))
  25. {
  26. Exception innerException = filterContext.Exception;
  27. if ((new HttpException(null, innerException).GetHttpCode() == 500) && this.ExceptionType.IsInstanceOfType(innerException))
  28. {
  29. string controllerName = (string)filterContext.RouteData.Values["controller"];
  30. string actionName = (string)filterContext.RouteData.Values["action"];
  31. HandleErrorInfo model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);
  32. ViewResult result = new ViewResult
  33. {
  34. ViewName = this.View,
  35. MasterName = this.Master,
  36. ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
  37. TempData = filterContext.Controller.TempData
  38. };
  39. filterContext.Result = result;
  40. filterContext.ExceptionHandled = true;
  41. filterContext.HttpContext.Response.Clear();
  42. filterContext.HttpContext.Response.StatusCode = 500;
  43. filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
  44. }
  45. }
  46. }
  47. }
  48. }