Web api global Exception Handler

来源:互联网 发布:潇湘馆的竹叶 知乎 编辑:程序博客网 时间:2024/06/15 12:39
 public class JgoExceptionFilterAttribute : ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            Utility.Logger.log.Error(
                "Type:" + actionExecutedContext.Exception.GetType().ToString() +
                ":Url:" + actionExecutedContext.Request.RequestUri +
                ":Body:" + GetBodyFromRequest(actionExecutedContext) +
                //":Message:" + actionExecutedContext.Exception.Message +
                //":StackTrace:" + actionExecutedContext.Exception.StackTrace +
                ":BaseMessage:" + actionExecutedContext.Exception.GetBaseException().Message +
                ":BaseStackTrace:" + actionExecutedContext.Exception.GetBaseException().StackTrace
                );


            //Log Exception
            //Utility.Logger.log.Error(actionExecutedContext.Exception.GetType().ToString() + ":" + actionExecutedContext.Exception.Message + ":" + actionExecutedContext.Exception.StackTrace + ":" + actionExecutedContext.Exception.StackTrace);


            base.OnException(actionExecutedContext);
        }


        private string GetBodyFromRequest(HttpActionExecutedContext context)
        {
            string data;
            using (var stream = context.Request.Content.ReadAsStreamAsync().Result)
            {
                if (stream.CanSeek)
                {
                    stream.Position = 0;
                }
                data = context.Request.Content.ReadAsStringAsync().Result;
            }
            return data;
        }


    }




 public class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Filters.Add(new JgoExceptionFilterAttribute());

0 0
原创粉丝点击