1. 程式人生 > >c# mvc 封裝返回對象

c# mvc 封裝返回對象

color ttr pan wget trace led lob trac class

將所有返回JsonContent對象進行再次封裝

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

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

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

最後全局註冊

        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new ResultFilterAttribute());
            filters.Add(new MvcExceptionFilterAttribute());
        }

c# mvc 封裝返回對象