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."));
     }
 }
Beispiel #2
0
        public static bool HasSingleModelError(this ModelStateDictionary modelStateDictionary, string propertyName, string expectedErrorMessage)
        {
            if (modelStateDictionary == null)
            {
                return(false);
            }

            if (modelStateDictionary.Count != 1)
            {
                return(false);
            }

            KeyValuePair <string, ModelState> firstError = modelStateDictionary.First();

            if (firstError.Key != propertyName)
            {
                return(false);
            }

            if (firstError.Value.Errors.Count != 1)
            {
                return(false);
            }

            string errorMessage = firstError.Value.Errors.Single().ErrorMessage;

            return(errorMessage == expectedErrorMessage);
        }
        public void ApplyCustomValidationSummaryOrdering_OneExtraRequested_ShouldIgnoreExtra()
        {
            var first      = "First";
            var second     = "Second";
            var third      = "Third";
            var missing    = "Missing";
            var firstPair  = new KeyValuePair <string, ModelState>(first, null);
            var secondPair = new KeyValuePair <string, ModelState>(second, null);
            var thirdPair  = new KeyValuePair <string, ModelState>(third, null);

            var modelState = new ModelStateDictionary();

            modelState.Add(thirdPair);
            modelState.Add(secondPair);
            modelState.Add(firstPair);

            modelState.ApplyCustomValidationSummaryOrdering(new List <string> {
                first, second, third, missing
            });

            Assert.Equal(3, modelState.Count);
            Assert.Equal(firstPair, modelState.First());
            Assert.Equal(secondPair, modelState.Skip(1).First());
            Assert.Equal(thirdPair, modelState.Skip(2).First());
        }
        public void ApplyCustomValidationSummaryOrdering_AllRequested_ShouldOrderAsRequested()
        {
            var first      = "First";
            var second     = "Second";
            var third      = "Third";
            var last       = "Last";
            var firstPair  = new KeyValuePair <string, ModelState>(first, null);
            var secondPair = new KeyValuePair <string, ModelState>(second, null);
            var thirdPair  = new KeyValuePair <string, ModelState>(third, null);
            var fourthPair = new KeyValuePair <string, ModelState>(last, null);

            var modelState = new ModelStateDictionary();

            modelState.Add(thirdPair);
            modelState.Add(secondPair);
            modelState.Add(fourthPair);
            modelState.Add(firstPair);

            modelState.ApplyCustomValidationSummaryOrdering(new List <string> {
                first, second, third, last
            });

            Assert.Equal(4, modelState.Count);
            Assert.Equal(firstPair, modelState.First());
            Assert.Equal(secondPair, modelState.Skip(1).First());
            Assert.Equal(thirdPair, modelState.Skip(2).First());
            Assert.Equal(fourthPair, modelState.Last());
        }
Beispiel #5
0
        public static ErrorResponse GetFirstErrorResponse(this ModelStateDictionary modelStateDictionary)
        {
            var modelState   = modelStateDictionary.First();
            var errorMessage = modelState.Value.Errors.FirstOrDefault()?.ErrorMessage;

            return(new ErrorResponse
            {
                Code = (int)HttpStatusCode.BadRequest,
                Message = errorMessage,
            });
        }
Beispiel #6
0
        /// <summary>
        /// Binds controller properties decorated with <see cref="FromRouteAttribute"/>
        /// using the current route values.
        /// </summary>
        /// <param name="controller">The controller to bind.</param>
        /// <remarks>You can call this method from <see cref="ApiController.Initialize"/>.</remarks>
        public static void BindRouteProperties(this ApiController controller)
        {
            if (controller == null)
            {
                throw new ArgumentNullException("controller");
            }

            var controllerData = controllerDataCache
                                 .GetOrAdd(controller.GetType(), (type) => new ControllerData(type));

            if (controllerData.Properties.Length == 0)
            {
                return;
            }

            var modelState = new ModelStateDictionary();

            var actionContext = new HttpActionContext {
                ControllerContext = controller.ControllerContext
            };

            var bindingContext = new ModelBindingContext {
                FallbackToEmptyPrefix = true,
                ModelState            = modelState
            };

            for (int i = 0; i < controllerData.Properties.Length; i++)
            {
                var propertyData = controllerData.Properties[i];

                propertyData.BindProperty(actionContext, bindingContext);

                if (!modelState.IsValid)
                {
                    break;
                }
            }

            if (!modelState.IsValid)
            {
                ModelError error = modelState.First(m => m.Value.Errors.Count > 0).Value.Errors.First();

                HttpStatusCode statusCode = HttpStatusCode.NotFound;
                string         message    = "Not Found";

                if (error.Exception != null)
                {
                    throw new HttpResponseException(controller.Request.CreateErrorResponse(statusCode, message, error.Exception));
                }

                throw new HttpResponseException(controller.Request.CreateErrorResponse(statusCode, message));
            }
        }
        public void ApplyTo_InvalidPatchOperations_AddsModelStateError(
            string op,
            string path,
            string from,
            string value,
            string error)
        {
            // Arrange
            var patch = new JsonPatchDocument <Customer>();

            patch.Operations.Add(new Operation <Customer>(op, path, from, value));
            var model      = new Customer();
            var modelState = new ModelStateDictionary();

            // Act
            patch.ApplyTo(model, modelState);

            // Assert
            Assert.Equal(1, modelState.ErrorCount);
            Assert.Equal(nameof(Customer), modelState.First().Key);
            Assert.Single(modelState.First().Value.Errors);
            Assert.Equal(error, modelState.First().Value.Errors.First().ErrorMessage);
        }
        public async Task GivenAResourceWithMissingResourceType_WhenParsing_ThenAnErrorShouldBeAddedToModelState()
        {
            var modelStateDictionary = new ModelStateDictionary();

            var result = await ReadRequestBody(Samples.GetJson("PatientMissingResourceType"), modelStateDictionary);

            Assert.False(result.IsModelSet);
            Assert.Equal(1, modelStateDictionary.ErrorCount);

            (_, ModelStateEntry entry) = modelStateDictionary.First();

            Assert.Single(entry.Errors);
            Assert.Equal(Api.Resources.ParsingError, entry.Errors.First().ErrorMessage);
        }
Beispiel #9
0
        public void InitProeprtyErrorElements__Test()
        {
            var propertyName = "Property";

            var modelstate = new ModelStateDictionary();

            modelstate.AddModelError(key: propertyName, errorMessage: $"{ propertyName } is required");

            var result = Initial.InitPropertyErrorElements(errors: modelstate.First().Value.Errors);

            Assert.IsTrue(condition: result.Count > 0);

            Assert.IsTrue(condition: result.First().Element.GetType() == typeof(Span));
        }
        public async Task GivenAResourceWithBadDecimal_WhenParsing_ThenAnErrorShouldBeAddedToModelState()
        {
            var modelStateDictionary = new ModelStateDictionary();
            var result = await ReadRequestBody(Samples.GetJson("MoneyWithWrongDecimal"), modelStateDictionary);

            Assert.False(result.IsModelSet);
            Assert.Equal(1, modelStateDictionary.ErrorCount);

            (_, ModelStateEntry entry) = modelStateDictionary.First();

            Assert.Single(entry.Errors);

            Assert.Contains("00", entry.Errors.First().ErrorMessage);
        }
      /// <summary>
      /// Binds controller properties decorated with <see cref="FromRouteAttribute"/>
      /// using the current route values.
      /// </summary>
      /// <param name="controller">The controller to bind.</param>
      /// <remarks>You can call this method from <see cref="ControllerBase.Initialize"/>.</remarks>
      public static void BindRouteProperties(this ControllerBase controller) {

         if (controller == null) throw new ArgumentNullException("controller");

         var controllerData = controllerDataCache
            .GetOrAdd(controller.GetType(), (type) => new ControllerData(type));

         if (controllerData.Properties.Length == 0) {
            return;
         }

         var modelState = new ModelStateDictionary();

         var bindingContext = new ModelBindingContext {
            FallbackToEmptyPrefix = true,
            ModelState = modelState
         };

         for (int i = 0; i < controllerData.Properties.Length; i++) {

            var propertyData = controllerData.Properties[i];

            propertyData.BindProperty(controller.ControllerContext, bindingContext);

            if (!modelState.IsValid) {
               break;
            }
         }

         if (!modelState.IsValid) {

            ModelError error = modelState.First(m => m.Value.Errors.Count > 0).Value.Errors.First(); 
            
            int statusCode = 404;
            string message = "Not Found";

            if (error.Exception != null) {
               throw new HttpException(statusCode, message, error.Exception);
            }

            throw new HttpException(statusCode, message);
         }
      }
        public async Task GivenAResourceWithMissingResourceType_WhenParsing_ThenAnErrorShouldBeAddedToModelState()
        {
            var modelStateDictionary = new ModelStateDictionary();
            var patient = Samples.GetJson("PatientMissingResourceType");
            var result  = await ReadRequestBody(patient, modelStateDictionary);

            Assert.False(result.IsModelSet);
            Assert.Equal(1, modelStateDictionary.ErrorCount);

            (_, ModelStateEntry entry) = modelStateDictionary.First();

            Assert.Single(entry.Errors);
            try
            {
                new FhirJsonParser().Parse <Resource>(patient);
            }
            catch (Exception ex)
            {
                Assert.Equal(string.Format(Api.Resources.ParsingError, ex.Message), entry.Errors.First().ErrorMessage);
            }
        }
Beispiel #13
0
 public BadModelException(ModelStateDictionary state) : base((int)ExceptionCodes.BAD_MODEL, $"{state.First().Key} {state.First().Value.Errors.First().ErrorMessage}")
 {
 }
 private static string GetTheFirstPropertyWithAnError(ModelStateDictionary modelState, string prefixValue)
 {
     return modelState.First(x => x.Value.Errors.Count() > 0 && x.Key.StartsWith(prefixValue)).Key;
 }