WebApiDoodle.Web.Filters.InvalidModelStateFilterAttribute.OnActionExecuting C# (CSharp) Method

OnActionExecuting() public method

public OnActionExecuting ( System.Web.Http.Controllers.HttpActionContext actionContext ) : void
actionContext System.Web.Http.Controllers.HttpActionContext
return void
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (!actionContext.ModelState.IsValid) {

                actionContext.Response = actionContext.Request.CreateErrorResponse(
                    HttpStatusCode.BadRequest, actionContext.ModelState);
            }
        }

Usage Example

        public void InvalidModelStateFilterAttribute_ShouldReturnTheResponseWithProperContentTypeIfTheModelStateIsNotValid()
        {
            //NOTE: This test might seems that we are here testing the framework
            //      stuff but we are not. We just make sure here that InvalidModelStateFilterAttribute
            //      really honors the conneg.

            //Arange
            var validateModelStateFilter = new InvalidModelStateFilterAttribute();
            var request = new HttpRequestMessage();
            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            var actionContext = ContextUtil.GetHttpActionContext(request);
            actionContext.ModelState.AddModelError("foo", "foo is invalid.");

            //NOTE: Here, the response is being returned through the CreateErrorResponse extension
            //      method of the HttpRequestMessage object. What this basically does is
            //      to pass an HttpError instance to another extension method, CreateResponse<T>.
            //      The CreateResponse<T> method looks at the configuration instance
            //      (yes, config shouldn't be null) and gets the IContentNegotiator service
            //      through Services. If we create a HttpConfiguration object with its
            //      parameterless ctor, the negotiator will be the type of DefaultContentNegotiator.
            //      DefaultContentNegotiator should negotiate properly here.

            //Act
            validateModelStateFilter.OnActionExecuting(actionContext);

            //Assert
            Assert.NotNull(actionContext.Response);
            Assert.True(actionContext.Response.Content.Headers.ContentType.MediaType.Equals("application/json", StringComparison.OrdinalIgnoreCase));
        }
All Usage Examples Of WebApiDoodle.Web.Filters.InvalidModelStateFilterAttribute::OnActionExecuting
InvalidModelStateFilterAttribute