ValidateModelAttribute.OnActionExecuting C# (CSharp) Method

OnActionExecuting() public method

public OnActionExecuting ( HttpActionContext actionContext ) : void
actionContext HttpActionContext
return void
            public override void OnActionExecuting(HttpActionContext actionContext)
            {
                if (actionContext.ModelState.IsValid == false)
                {
                    actionContext.Response = actionContext.Request.CreateErrorResponse(
                        HttpStatusCode.BadRequest, actionContext.ModelState);
                }
            }
        }

Usage Example

Example #1
0
        public void ValidateModelNotValid()
        {
            var actionContext = GetContext(true);
            var sa            = new ValidateModelAttribute();

            sa.OnActionExecuting(actionContext);
            var result = actionContext.Result as BadRequestObjectResult;

            Assert.NotNull(result);
            var errorDictionary = result.Value as SerializableError;

            Assert.NotNull(errorDictionary);
            Assert.True(errorDictionary.ContainsKey("P1"));
            Assert.True(errorDictionary.ContainsKey("P2"));
            var p1 = errorDictionary["P1"] as string[];

            Assert.NotNull(p1);
            Assert.AreEqual(1, p1.Length);
            Assert.AreEqual("bad", p1[0]);
            var p2 = errorDictionary["P2"] as string[];

            Assert.NotNull(p2);
            Assert.AreEqual(1, p2.Length);
            Assert.AreEqual("worse", p2[0]);
        }
All Usage Examples Of ValidateModelAttribute::OnActionExecuting
ValidateModelAttribute