예제 #1
0
 public ApiResult(ModelStateDictionary modelState)
     : this()
 {
     if (modelState.Any(m => m.Value.Errors.Count > 0))
     {
         StatusCode = 400;
         Message = "The model submitted was invalid. Please correct the specified errors and try again.";
         ModelErrors = modelState.SelectMany(m => m.Value.Errors.Select(me => new ModelError { FieldName = m.Key, ErrorMessage = me.ErrorMessage }));
     }
 }
예제 #2
0

        
예제 #3
0
 public ApiError(ModelStateDictionary modelState)
 {
     this.isError = true;
     if (modelState != null && modelState.Any(m => m.Value.Errors.Count > 0))
     {
         message = "Please correct the specified errors and try again.";
         //errors = modelState.SelectMany(m => m.Value.Errors).ToDictionary(m => m.Key, m=> m.ErrorMessage);
         //errors = modelState.SelectMany(m => m.Value.Errors.Select( me => new KeyValuePair<string,string>( m.Key,me.ErrorMessage) ));
         //errors = modelState.SelectMany(m => m.Value.Errors.Select(me => new ModelError { FieldName = m.Key, ErrorMessage = me.ErrorMessage }));
     }
 }
 public static ActionResult HttpBadRequest(ModelStateDictionary ModelState)
 {
     if (ModelState.Any() && ModelState.First().Value.Errors.Any())
     {
         return(HttpBadRequest(
                    string.Format("Error(s) in request model: {0}.", ModelState.First().Value.Errors.First().ErrorMessage)));
     }
     else
     {
         return(HttpBadRequest("Error in request model."));
     }
 }
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        ModelStateDictionary modelState =
            filterContext.Controller.ViewData.ModelState;

        if (modelState.Any(kvp => kvp.Value.Errors.Count > 0))
        {
            filterContext.Result = CreateResult(filterContext,
                                                modelState.Where(kvp => kvp.Value.Errors.Count > 0));
        }
        base.OnActionExecuting(filterContext);
    }
예제 #7
0
 public ResponseException(ModelStateDictionary modelState)
 {
     if (modelState != null && modelState.Any(m => m.Value.Errors.Count > 0))
     {
         var stringLocalizer = EngineContext.Current.Resolve <IStringLocalizer <ApiResponseMessage> >();
         ErrorMessage     = stringLocalizer[ApiResponseMessage.ValidationException];
         ValidationErrors = modelState.Keys
                            .SelectMany(key => modelState[key].Errors.Select(x => new ModelValidation(key, x.ErrorMessage)))
                            .ToList();
         ErrorType = ErrorTypes.InvalidRequest;
     }
 }
예제 #8
0
 public ApiResult(ModelStateDictionary modelState)
     : this()
 {
     if (modelState.Any(m => m.Value.Errors.Any()))
     {
         StatusCode  = 400;
         Message     = "The model submitted was invalid. Please correct the specified errors and try again.";
         ModelErrors = modelState
                       .Where(m => m.Value.Errors.Any())
                       .ToDictionary(m => m.Key, m => m.Value.Errors.Select(me => me.ErrorMessage));
     }
 }
예제 #9
0

        
예제 #10
0
 public ApiResult(ModelStateDictionary modelState)
     : this()
 {
     if (modelState.Any(m => m.Value.Errors.Count > 0))
     {
         StatusCode  = 400;
         Message     = "The model submitted was invalid. Please correct the specified errors and try again.";
         ModelErrors = modelState
                       .SelectMany(m => m.Value.Errors.Select(me => new ModelError
         {
             FieldName    = m.Key,
             ErrorMessage = me.ErrorMessage
         }));
     }
 }
예제 #11
0
        public static IEnumerable <ModelStateError> AllModelStateErrors(this ModelStateDictionary modelState)
        {
            if (modelState == null || !modelState.Any(m => m.Value.Errors.Count > 0))
            {
                return(null);
            }

            var result = from ms in modelState
                         where ms.Value.Errors.Any()
                         let fieldKey = ms.Key
                                        let errors = ms.Value.Errors
                                                     from error in errors
                                                     select new ModelStateError(fieldKey, error.ErrorMessage);

            return(result);
        }
예제 #12
0
        /// <summary>
        /// Create a new API Error from model state dictionary
        /// Error values.
        /// </summary>
        /// <param name="modelState"></param>
        public ApiError(ModelStateDictionary modelState)
        {
            isError = true;
            if (modelState != null && modelState.Any(m => m.Value.Errors.Count > 0))
            {
                var errors = new ValidationErrorCollection();
                foreach (var modelStateItem in modelState)
                {
                    var key = modelStateItem.Key;
                    foreach (var val in modelStateItem.Value.Errors)
                    {
                        errors.Add(val.ErrorMessage, key, key);
                    }
                }

                message = errors.ToString();
            }
        }
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        string order  = (string)actionContext.ActionArguments["order"];
        string sortBy = (string)actionContext.ActionArguments["sortby"];
        var    states = new ModelStateDictionary();

        if (!order.Equals("ASC") && !order.Equals("DESC"))
        {
            states.AddModelError("order", "Order has to be DESC or ASC");
        }
        if (!new[] { "username", "name" }.Contains(sortBy.ToLower()))
        {
            states.AddModelError("sortby", "Not A Valid Sorting Column");
        }
        if (states.Any())
        {
            actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, states);
        }
    }
예제 #14
0
 /// <summary>
 /// Al atributo Error se agrega el listado de mensajes de error del modelo y se agrega el listado de mensajes adicionales
 /// Si se agregaron los mensajes se hace Error.error=TRUE
 /// </summary>
 /// <param name="pJsonResponse"></param>
 /// <param name="pModelStateDictionary">Mensajes de error del modelo</param>
 /// <param name="pAditionalMessage">Listado de mensajes adicionales</param>
 /// <returns></returns>
 public static JsonResponse SetErrorMessage(this JsonResponse pJsonResponse, ModelStateDictionary pModelStateDictionary, ICollection <string> pAditionalMessage)
 {
     try
     {
         if (pModelStateDictionary != null && pModelStateDictionary.Any())
         {
             pJsonResponse.Error.AddMessage(pModelStateDictionary.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage).ToList());
         }
         if (pAditionalMessage != null && pAditionalMessage.Any())
         {
             pJsonResponse.Error.AddMessage(pAditionalMessage);
         }
         pJsonResponse.Error.error = pJsonResponse.Error.message.Count > 0;
         return(pJsonResponse);
     }
     catch (Exception vE)
     {
         throw vE;
     }
 }
예제 #15
0
 /// <summary>
 /// 获取模型绑定中的ErrMsg
 /// </summary>
 /// <param name="dict"></param>
 /// <returns></returns>
 public static string GetErrMsg(this ModelStateDictionary dict)
 {
     if (dict.IsValid || !dict.Any())
     {
         return("");
     }
     foreach (string key in dict.Keys)
     {
         ModelState tmp = dict[key];
         if (tmp.Errors.Any())
         {
             var firstOrDefault = tmp.Errors.FirstOrDefault();
             if (firstOrDefault != null)
             {
                 return(firstOrDefault.ErrorMessage);
             }
         }
     }
     return("");
 }
예제 #16
0
 /// <summary>
 /// 获取模型绑定中的第一条错误信息
 /// </summary>
 /// <param name="msDictionary"></param>
 /// <returns></returns>
 public static string GetFirstErrMsg(this ModelStateDictionary msDictionary)
 {
     if (msDictionary.IsValid || !msDictionary.Any())
     {
         return("");
     }
     foreach (string key in msDictionary.Keys)
     {
         ModelStateEntry tempModelState = msDictionary[key];
         if (tempModelState.Errors.Any())
         {
             var firstOrDefault = tempModelState.Errors.FirstOrDefault();
             if (firstOrDefault != null)
             {
                 return(firstOrDefault.ErrorMessage);
             }
         }
     }
     return("");
 }
예제 #17
0
        protected IHttpActionResult ErrorResult(ModelStateDictionary modelState, int httpStatus = 400, int errorCode = 2)
        {
            HttpStatusCode requestStatusCode;

            if (!Enum.TryParse(httpStatus.ToString(), out requestStatusCode))
            {
                requestStatusCode = HttpStatusCode.BadRequest;
            }


            var errorResponse = new HttpResponseMessage(requestStatusCode)
            {
                RequestMessage = Request
            };

            if (modelState == null || !modelState.Any())
            {
                return(ResponseMessage(errorResponse));
            }


            var modelStateErrors = modelState.Values.SelectMany(m => m.Errors).Select(e => e.ErrorMessage).ToList();

            var resultErrorEntity = new ExecutionResultEntity <object>
            {
                error = new ExecutionErrorDetails
                {
                    Code    = errorCode,
                    Message = string.Join(" ", modelStateErrors)
                }
            };

            errorResponse.Content =
                new StringContent(JsonConvert.SerializeObject(resultErrorEntity,
                                                              new JsonSerializerSettings {
                NullValueHandling = NullValueHandling.Ignore
            }));

            return(ResponseMessage(errorResponse));
        }
예제 #18
0
        /// <summary>
        /// 获取ModelState所有错误信息,间隔符间隔
        /// </summary>
        /// <param name="splitStr">间隔符</param>
        /// <returns></returns>
        public static string GetAllErrMsgStr(this ModelStateDictionary msDictionary, string splitStr)
        {
            var returnStr = "";

            if (msDictionary.IsValid || !msDictionary.Any())
            {
                return(returnStr);
            }

            //获取所有错误的Key
            foreach (string key in msDictionary.Keys)
            {
                ModelStateEntry tempModelState = msDictionary[key];
                if (tempModelState.Errors.Any())
                {
                    var errorList = tempModelState.Errors.ToList();
                    foreach (var item in errorList)
                    {
                        returnStr += item.ErrorMessage + splitStr;
                    }
                }
            }
            return(returnStr);
        }
예제 #19
0
        /// <summary>
        ///  获取错误信息列表
        /// </summary>
        /// <param name="msDictionary"></param>
        /// <returns></returns>
        public static List <string> GetErrMsgList(this ModelStateDictionary msDictionary)
        {
            var list = new List <string>();

            if (msDictionary.IsValid || !msDictionary.Any())
            {
                return(list);
            }

            //获取所有错误的Key
            foreach (string key in msDictionary.Keys)
            {
                ModelStateEntry tempModelState = msDictionary[key];
                if (tempModelState.Errors.Any())
                {
                    var errorList = tempModelState.Errors.ToList();
                    foreach (var item in errorList)
                    {
                        list.Add(item.ErrorMessage);
                    }
                }
            }
            return(list);
        }
예제 #20
0
 //returns true if an error message exists in the modelstate
 public static bool ContainsErrorMessage(this ModelStateDictionary modelState, string errorMessage)
 {
     return(modelState.Any(ms => ms.Value.Errors.Count(e => e.ErrorMessage == errorMessage) > 0));
 }
예제 #21
0
        public static void CleanModelErrors <TModel>(this Controller controller)
        {
            Type containerType = typeof(TModel);
            //Save the old modelstate
            var oldModelState = new ModelStateDictionary();

            foreach (KeyValuePair <string, ModelStateEntry> modelState in controller.ModelState)
            {
                string propertyName = modelState.Key;
                foreach (ModelError error in modelState.Value.Errors)
                {
                    bool exists = oldModelState.Any(
                        m => m.Key == propertyName && m.Value.Errors.Any(e => e.ErrorMessage == error.ErrorMessage));

                    //add the inline message if it doesnt already exist
                    if (!exists)
                    {
                        oldModelState.AddModelError(propertyName, error.ErrorMessage);
                    }
                }
            }

            //Clear the model state ready for refill
            controller.ModelState.Clear();

            foreach (KeyValuePair <string, ModelStateEntry> modelState in oldModelState)
            {
                //Get the property name
                string propertyName = modelState.Key;

                //Get the validation attributes
                PropertyInfo propertyInfo             = string.IsNullOrWhiteSpace(propertyName) ? null : containerType.GetPropertyInfo(propertyName);
                List <ValidationAttribute> attributes = propertyInfo == null
                    ? null
                    : propertyInfo.GetCustomAttributes(typeof(ValidationAttribute), false).ToList <ValidationAttribute>();

                //Get the display name
                var displayNameAttribute =
                    propertyInfo?.GetCustomAttributes(typeof(DisplayNameAttribute), false).FirstOrDefault() as DisplayNameAttribute;
                var displayAttribute =
                    propertyInfo?.GetCustomAttributes(typeof(DisplayAttribute), false).FirstOrDefault() as DisplayAttribute;
                string displayName = displayNameAttribute != null ? displayNameAttribute.DisplayName :
                                     displayAttribute != null ? displayAttribute.Name : propertyName;

                foreach (ModelError error in modelState.Value.Errors)
                {
                    string title       = string.IsNullOrWhiteSpace(propertyName) ? error.ErrorMessage : null;
                    string description = !string.IsNullOrWhiteSpace(propertyName) ? error.ErrorMessage : null;

                    if (error.ErrorMessage.Like("The value * is not valid for *."))
                    {
                        title       = "There's a problem with your values.";
                        description = "The value here is invalid.";
                    }

                    if (attributes != null && attributes.Any())
                    {
                        ValidationAttribute attribute = attributes.FirstOrDefault(a => a.FormatErrorMessage(displayName) == error.ErrorMessage);
                        if (attribute != null)
                        {
                            string             validatorKey = $"{containerType.Name}.{propertyName}:{attribute.GetType().Name.TrimSuffix("Attribute")}";
                            CustomErrorMessage customError  = CustomErrorMessages.GetValidationError(validatorKey);
                            if (customError != null)
                            {
                                title       = attribute.FormatError(customError.Title, displayName);
                                description = attribute.FormatError(customError.Description, displayName);
                            }
                        }
                    }

                    //add the summary message if it doesnt already exist
                    if (!string.IsNullOrWhiteSpace(title) &&
                        !controller.ModelState.Any(m => m.Key == "" && m.Value.Errors.Any(e => e.ErrorMessage == title)))
                    {
                        controller.ModelState.AddModelError("", title);
                    }

                    //add the inline message if it doesnt already exist
                    if (!string.IsNullOrWhiteSpace(description) &&
                        !string.IsNullOrWhiteSpace(propertyName) &&
                        !controller.ModelState.Any(
                            m => m.Key.EqualsI(propertyName) && m.Value.Errors.Any(e => e.ErrorMessage == description)))
                    {
                        controller.ModelState.AddModelError(propertyName, description);
                    }
                }
            }
        }