Model validation in web API - exception thrown from throw statement?

I saw model validationfrom here (in the section:) Handling Validation Errors.

Below is a snippet of code in Web API

public class ValidateModel : ActionFilterAttribute
    {
        public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            if (actionContext.ModelState.IsValid == false)
            {
                actionContext.Response = actionContext.Request.CreateErrorResponse(
                    HttpStatusCode.BadRequest, actionContext.ModelState);
            }

            base.OnActionExecuting(actionContext);
        }
    }

The problem is upon validation of model, if there were any errors, an exception it assigns an model state invalid.

And after that, before moving on to the actual method (which is decorated with this attribute [ValidateModel]), the WebAPI simply returns a 400 request.

But how? Which function returns HTTP 400?

What happens after executing this method? Where is the control flow?

EDIT:

The action that I apply to this attribute is normal.

[ValidateModel]
public IHttpActionResult Post([FromBody]Request)
{
//do normal business logics here.
return Ok(SuccessMessage);
}
+4
4

, -

. , OnActionExecuting , , , OnActionExecuted . OnActionExecuting -

public class ValidateModel : ActionFilterAttribute
{
    public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        if (actionContext.ModelState.IsValid == false)
        {
            actionContext.Response = actionContext.Request.CreateErrorResponse(
                HttpStatusCode.BadRequest, actionContext.ModelState);
        }

        base.OnActionExecuting(actionContext);
    }
}

, :

 if (actionContext.ModelState.IsValid == false)
        {
            actionContext.Response = actionContext.Request.CreateErrorResponse(
                HttpStatusCode.BadRequest, actionContext.ModelState);
        }

, OnActionExecuting . 400 , , , , , . , , .

, , -

base.OnActionExecuting(actionContext);

http://msdn.microsoft.com/en-us/library/system.web.mvc.actionfilterattribute(v = vs .118).aspx

+4

, Application_Error Global.asax , .

+1

OnActionExecuting, , . actionContext.Response , 400 , , . , -. jquery asp.net, webapi . , . , , . , 400. 200, , , -api 200. 200 webapi, EF , . catch try, , . URL- , .

+1
source

If your data type is Requestdefined as structor abstract class, it cannot be created, and this may be the probable cause. If it is a structure, just make it Nullableif it is an abstract class or interface, you can either create your own ModelBinderto work with creation, or change it using a specific implementation.

+1
source

Source: https://habr.com/ru/post/1544135/


All Articles