public override void OnActionExecuting(HttpActionContext actionContext) { if (!actionContext.ModelState.IsValid) { ErrorInfo error = new ErrorInfo() { IsModelValidateError = true, ModelState = actionContext.ModelState }; actionContext.Response = actionContext.Request.CreateResponse( HttpStatusCode.OK, new AjaxResponse(error)); //context.Response.Content = new ObjectContent<AjaxResponse>(new AjaxResponse(_errorInfo), new JsonMediaTypeFormatter()); } }
/// <summary> /// 错误拦截器 /// </summary> /// <param name="context">当前 action 上下文</param> public override void OnException(HttpActionExecutedContext context) { ErrorInfo _errorInfo = new ErrorInfo(); _errorInfo.Exception = context.Exception; // context.Response = context.Request.CreateResponse( // HttpStatusCode.OK, // new AjaxResponse(_errorInfo) // ); /// 在 拦截 ajax 错误时 上面写法 返回 500 if(_errorInfo.Exception.InnerException!=null) { //提示友好信息 _errorInfo.Message = _errorInfo.Exception.InnerException.Message; context.Response = new HttpResponseMessage(HttpStatusCode.OK); context.Response.Content = new ObjectContent<AjaxResponse>(new AjaxResponse(_errorInfo), new JsonMediaTypeFormatter()); } else { context.Response = new HttpResponseMessage(HttpStatusCode.OK); context.Response.Content = new ObjectContent<AjaxResponse>(new AjaxResponse(_errorInfo), new JsonMediaTypeFormatter()); } }
public DynamicControllerExceptionFilterAttribute(ErrorInfo errorInfo) { _errorInfo = errorInfo; }