c# mvc 封裝返回對象

將全部返回JsonContent對象進行再次封裝json

public class ResultFilterAttribute : System.Web.Mvc.ActionFilterAttribute
    {
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {

            if (filterContext.Exception != null)
            {
                base.OnActionExecuted(filterContext);
                return;
            }
            if (filterContext.Result is JsonResult)
            {
                var invokeResult = new InvokeResult<object>
                {
                    Success = true
                };
                var result = filterContext.Result as JsonResult;
                invokeResult.Data = result.Data;
                result.Data = invokeResult;
                base.OnActionExecuted(filterContext);
                return;
            }

            base.OnActionExecuted(filterContext);
            return;

        }
    }

 

 

對異常信息處理,避免黃頁顯示ide

 

public class MvcExceptionFilterAttribute : IExceptionFilter
    {
        public void OnException(ExceptionContext filterContext)
        {

            var invokeResult = new InvokeResult<object>();
            
            if(filterContext.Exception is DomainException)
            {
                invokeResult.Message = filterContext.Exception.Message;
            }
            else
            {
                invokeResult.Message = filterContext.Exception.Message + (filterContext.Exception.StackTrace??"");
                //記錄日誌
            }
            var jsonResult = new JsonResult
            {
                Data = invokeResult,
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
            filterContext.ExceptionHandled = true;
            filterContext.Result = jsonResult;

            
        }
    }

 

最後全局註冊spa

        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new ResultFilterAttribute());
            filters.Add(new MvcExceptionFilterAttribute());
        }
相關文章
相關標籤/搜索