0

Using JObject to pass data to webapi, how do you perform model validation of the objects returned from the JObject? I am using angurlarjs for binding and DTO for my model.

 [System.Web.Http.HttpPost]
        public HttpResponseMessage InsertSchoolBranch(JObject jsonData)
        {

            try
            {
                dynamic json = jsonData;    
                JObject jbranchInfo = json.branchInfo;
                JObject jbranchPolicy = json.branchPolicy;


                var branchInfo = jbranchInfo.ToObject<SchoolBranch>();
                var branchPolicy = jbranchPolicy.ToObject<SchoolPolicy>();

                int schoolId = Convert.ToInt32(UserDataPieces(2));
                int userId = Convert.ToInt32(UserDataPieces(0));

                unitOfWork.SchoolManagerRepository.InsertSchoolBranch(branchInfo, branchPolicy, userId, schoolId, ref message);

                return new HttpResponseMessage(HttpStatusCode.OK);
            }
            catch (UnauthorizedAccessException)
            {
                return Request.CreateResponse(HttpStatusCode.Unauthorized);
            }
            catch (Exception)
            {
                return Request.CreateResponse(HttpStatusCode.InternalServerError);


            }


        }
codegrid
  • 977
  • 2
  • 13
  • 33
  • If you post a strongly typed model instead of the dynamic `JObject` you can decorate your model properties with validation attributes and check for `ModelState.IsValid` in your action. – Jasen May 05 '15 at 18:02
  • Hello @Jasen, tried that but it didn't work. It throws up this error `Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.` – codegrid May 05 '15 at 19:23
  • 1
    @uikrosoft could you share complete code and request details when you get this error – Victor May 05 '15 at 20:10
  • See [here](http://stackoverflow.com/questions/7795300/validation-failed-for-one-or-more-entities-see-entityvalidationerrors-propert) and share some details about your error. – Jasen May 06 '15 at 00:41

1 Answers1

0

If you want to validate the input data consider decorating them with custom ActionFilterAttributes.

[RequiresJsonBody("SchoolBranch","SchoolPolicy")]
public HttpResponseMessage InsertSchoolBranch(JObject jsonData)
{
    // Stuff...
}

or maybe use some tuple as model

public class RequiresJsonBody : ActionFilterAttribute
{
    private string paramName;

    public RequiresJsonBody (string paramName)
    {
        this.paramName = paramName;
    }

    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        IDictionary<string, string> errors = new Dictionary<string, string>();

        // Validate incoming. Add key / error messages to dictionary...

        foreach (var err in errors)
        {
            actionContext.ModelState.AddModelError(err.Key, err.Value);
        }

        if (!actionContext.ModelState.IsValid
            && errors.Keys.Count > 0)
        {
            actionContext.Response
                = actionContext.Request.CreateErrorResponse(
                    HttpStatusCode.BadRequest,
                    String.Join(" ", errors.Values.ToArray()));
        }
    }
}
Jonas Jerndin
  • 136
  • 1
  • 4
  • Hello @Jonas, I followed your example but I am still getting `Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.` I did a trace and discovered it enters `OnActionExecuting` with no errors. – codegrid May 05 '15 at 23:47
  • @uikrosoft Maybe you should look at the exception. Seems that you might have a db-model problem. Try to use some debug implementation for unitOfWork.SchoolManagerRepository that just writes the models to the debugger instead of going to entity framework. Or check out http://stackoverflow.com/questions/7795300/validation-failed-for-one-or-more-entities-see-entityvalidationerrors-propert – Jonas Jerndin May 06 '15 at 06:00