WebErrorAttribute

using System;
using System.Collections.Generic;
using System.Linq;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace eyhome.Helper
{
    public class WebErrorAttribute : FilterAttribute, IExceptionFilter
    {
        private static object errorLock = new object();
        public void OnException(ExceptionContext filterContext)
        {
            //获取捕获到的异常信息
            Exception ex = filterContext.Exception;

            #region 写异常日志
            Task.Factory.StartNew(() =>
            {
                lock (errorLock)
                {
                    string FileName = DateTime.Now.ToString("yyyyMMdd") + ".txt";
                    string ForderName = filterContext.HttpContext.Server.MapPath("~/ErrorLog/" + FileName);
                    using (StreamWriter sr = File.AppendText(ForderName))
                    {
                        sr.WriteLine("");
                        sr.WriteLine("");
                        sr.WriteLine("错误时间:" + DateTime.Now.ToString());
                        sr.WriteLine("错误文件:" + filterContext.HttpContext.Request.RawUrl);
                        sr.WriteLine("错误原因:" + ex.Message);
                        sr.WriteLine("错误内容:" + ex.ToString());
                        sr.WriteLine("*************************************************************");
                    }
                }
            });
            #endregion

            string errMessage = WebError.setMessage(ex);
            //设置返回视图字典
            ViewDataDictionary vdiy = new ViewDataDictionary();
            vdiy.Add("Message", errMessage);
            //定义返回视图,代替页面请求实际视图。
            //MasterName 视图模板页面名称
            //ViewData   字典 可以在视图中使用:ViewData["字典名称"]或者ViewBag.字典名称 来调用
            //ViewName   视图名称
            //如果为ajax请求,则返回Json格式数据
            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                //var result = new JsonResult { Data = new { @success = false, @message = errMessage }, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
                var result = new ContentResult { Content = string.Format("<script>alert(‘{0}‘);window.location.back();</script>", errMessage) };
                filterContext.Result = result;
            }
            //else if (!filterContext.HttpContext.Request.IsAjaxRequest())//普通请求直接返回错误视图
            //{
            //    var result = new ViewResult { MasterName = null, ViewData = vdiy, ViewName = "Errors" };
            //    filterContext.Result = result;
            //}
            else
            {
                var result = new ViewResult { MasterName = null, ViewData = vdiy, ViewName = "Errors" };
                filterContext.Result = result;
            }
            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
        }
    }
    class WebError
    {
        /// <summary>
        /// 对不同的异常信息返回不同的处理结果
        /// </summary>
        /// <param name="ex"></param>
        /// <returns></returns>
        public static string setMessage(Exception ex)
        {          

            if (ex is HttpRequestValidationException)
            {
                return "您输入了非法字符串,禁止输入HTML代码";
            }

            if (ex is ArgumentException)
            {
                return "参数错误,请查检地址是否正确";
            }

            if (ex is HttpUnhandledException)
            {
                return "系统繁忙,请稍后重试";
            }

            if (ex is InvalidOperationException)
            {
                return "无法完成该操作";
            }

            if (ex is FormatException)
            {
                return "输入字符串的格式不正确";
            }
            if (ex is ArgumentException)
            {
                return "操作参数不足";
            }
            if (ex is HttpException)
            {
                return "HTTP页面错误";
            }
            if (ex is ValidationException)
            {
                ValidationException vex = ex as ValidationException;
                return "数据验证失败:" + vex.ValidationResult.ErrorMessage;
            }
            return ex.Message;

        }

    }
}
时间: 2024-10-27 13:28:45

WebErrorAttribute的相关文章