public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (actionContext == null)
            {
                throw new ArgumentNullException("actionContext");
            }
            HttpRequestMessage request = actionContext.Request;

            if (request == null)
            {
                throw new ArgumentException("context.request");
            }

            if (!actionContext.ModelState.IsValid)
            {
                IHttpActionResult result = new InvalidModelStateResult(
                    actionContext.ModelState,
                    true,
                    actionContext.RequestContext.Configuration.Services.GetContentNegotiator(),
                    actionContext.Request,
                    actionContext.RequestContext.Configuration.Formatters);
                var response = result.ExecuteAsync(CancellationToken.None);
                actionContext.Response = response.Result;
                return;
            }
            base.OnActionExecuting(actionContext);
        }
        public void TestInvalidModelStateResult_should_work_as_expected_with_method_without_arguments()
        {
            ApiControllerHttpActionResultActionTester actionTester = _controllerTester.Action(x => x.HttpActionResultActionWithoutArguments);

            _controller.HttpActionResult = new InvalidModelStateResult(new ModelStateDictionary(), _controller);

            InvalidModelStateResult result          = null;
            InvalidModelStateResult validatedResult = null;
            bool validateWasCalled = false;

            Action action = () =>
            {
                result = actionTester.TestInvalidModelStateResult(r =>
                {
                    validatedResult   = r;
                    validateWasCalled = true;
                });
            };

            action.Should().NotThrow();
            result.Should().Be(_controller.HttpActionResult);
            validateWasCalled.Should().BeTrue();
            validatedResult.Should().Be(_controller.HttpActionResult);

            _controller.HttpActionResult = _okResult;
            action.Should().Throw <ControllerTestException>().WithMessage(
                "Expected IHttpActionResult type System.Web.Http.Results.InvalidModelStateResult. Actual: System.Web.Http.Results.OkResult.");
        }
        public static ModelStateDictionary GetModelStateDictionary(this IHttpActionResult result)
        {
            InvalidModelStateResult modelStateResult = result as InvalidModelStateResult;

            if (modelStateResult == null)
            {
                return(null);
            }

            ModelStateDictionary modelStateDictionary = modelStateResult.ModelState;

            return(modelStateDictionary);
        }
        public override async Task OnActionExecutingAsync(HttpActionContext actionContext,
                                                          CancellationToken cancellationToken)
        {
            if (!actionContext.ModelState.IsValid)
            {
                IHttpActionResult result = new InvalidModelStateResult(
                    actionContext.ModelState,
                    true,
                    actionContext.RequestContext.Configuration.Services.GetContentNegotiator(),
                    actionContext.Request,
                    actionContext.RequestContext.Configuration.Formatters);
                actionContext.Response = await result.ExecuteAsync(cancellationToken);

                return;
            }
            await base.OnActionExecutingAsync(actionContext, cancellationToken);
        }
Beispiel #5
0
        /// <summary>
        /// 获得错误信息
        /// </summary>
        /// <param name="validResult"></param>
        /// <returns></returns>
        public static string GetMsg(InvalidModelStateResult validResult)
        {
            var msg = "";

            var firstOrDefault = validResult.ModelState.Values.FirstOrDefault();

            if (firstOrDefault == null)
            {
                return(msg);
            }
            var modelError = firstOrDefault.Errors.FirstOrDefault();

            if (modelError != null)
            {
                msg = modelError.ErrorMessage;
            }

            return(msg);
        }
        public void PostInvalidRouteStateTest()
        {
            RouteDTO mockedRoute = this.getMockedRoutes().ElementAt(0);

            this.routesAdminService.CreateRoute(Arg.Any <RouteDTO>()).Returns(mockedRoute);
            this.routesController.ModelState.AddModelError("Name", "Error Message.");

            RouteDTO route = new RouteDTO()
            {
                Cost = 10
            };

            IHttpActionResult actionResult = this.routesController.Post(route);

            // assertions
            this.routesAdminService.DidNotReceive().CreateRoute(route);

            InvalidModelStateResult invalidModelStateResult = actionResult as InvalidModelStateResult;

            Assert.IsNotNull(invalidModelStateResult);
        }
        public void PostInvalidPointStateTest()
        {
            PointDTO mockedPoint = this.getMockedPoints().ElementAt(0);

            this.pointsAdminService.CreatePoint(Arg.Any <PointDTO>()).Returns(mockedPoint);
            this.pointsController.ModelState.AddModelError("Name", "Error Message.");

            PointDTO point = new PointDTO()
            {
                Name = "A"
            };

            IHttpActionResult actionResult = this.pointsController.Post(point);

            // assertions
            this.pointsAdminService.DidNotReceive().CreatePoint(point);

            InvalidModelStateResult invalidModelStateResult = actionResult as InvalidModelStateResult;

            Assert.IsNotNull(invalidModelStateResult);
        }
Beispiel #8
0
        public void Get_ConfirmEmail_Should_Return_BadRequest_ModelState()
        {
            //Action
            GenerateData("1", new[] { "NoRoles" });
            RegisterController registerController = new RegisterController(userService.Object,
                                                                           tokenValidation.Object,
                                                                           incUserMapper.Object,
                                                                           mesService.Object);

            //Arrange
            int    userId = 0;
            string code   = "";

            Assert.AreEqual(userId, 0);
            Assert.AreEqual(code, "");

            var actual           = registerController.ConfirmEmail(userId, code);
            var badRequestResult = new BadRequestResult(registerController);
            InvalidModelStateResult invalidModel = new InvalidModelStateResult(registerController.ModelState, registerController);

            //Assert
            Assert.IsNotNull(actual);
            Assert.AreEqual(actual.GetType(), invalidModel.GetType());
        }
        public void Get_ConfirmEmail_Should_Return_BadRequest_ModelState()
        {
            //Action
            GenerateData("1", new[] { "NoRoles" });
            RegisterController registerController = new RegisterController(userService.Object,
                tokenValidation.Object,
                incUserMapper.Object,
                mesService.Object);

            //Arrange
            int userId = 0;
            string code = "";

            Assert.AreEqual(userId, 0);
            Assert.AreEqual(code, "");

            var actual = registerController.ConfirmEmail(userId, code);
            var badRequestResult = new BadRequestResult(registerController);
            InvalidModelStateResult invalidModel = new InvalidModelStateResult(registerController.ModelState, registerController);
            //Assert
            Assert.IsNotNull(actual);
            Assert.AreEqual(actual.GetType(), invalidModel.GetType());
        }