public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { //before controller if (!context.ModelState.IsValid) { var errorsInModel = context.ModelState.Where(x => x.Value.Errors.Count > 0) .ToDictionary(x => x.Key, x => x.Value.Errors.Select( x => x.ErrorMessage)).ToArray(); var errorResponse = new ErrorResponse(); foreach (var error in errorsInModel) { foreach (var subError in error.Value) { var errorModel = new ErrorModels() { FieldName = error.Key, Message = subError }; errorResponse.Errors.Add(errorModel); } } context.Result = new BadRequestObjectResult(errorResponse); return; } await next(); }
public override void OnException(HttpActionExecutedContext actionExecutedContext) { ErrorModels models = new ErrorModels() { ActionName = actionExecutedContext.ActionContext.ActionDescriptor.ActionName, ControllerName = actionExecutedContext.ActionContext.ControllerContext.ControllerDescriptor.ControllerName, ErrorMessage = actionExecutedContext.Exception.InnerException.InnerException.Message }; var errroObject = JsonConvert.SerializeObject(models); actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(HttpStatusCode.BadRequest, errroObject); //Log }