2

I am not sure how to validate a model in web API, when we receive it as a serialized string.

I use DataAnnotations on my model for validation purposes, and I usually do this:

public IHttpActionResult Save([FromBody] IEnumerable<User> users)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    // ...
}

In this specific case, the "model" is coming from a serialized string:

public IHttpActionResult Save()
{
    string Data = HttpContext.Current.Request.Form["Data"];
    IEnumerable<User> users = JsonConvert.DeserializeObject<IEnumerable<User>>(Data);

    // ...
}

How could I possibly validate this?

1

1 Answer 1

1

Following the example above:

        // Validate
        Validate<List<User>>(user);

        if (!ModelState.IsValid)
        {
            return new InvalidModelStateResult(ModelState, true, new DefaultContentNegotiator(), Request, new MediaTypeFormatter[] { new JsonMediaTypeFormatter() }); // Force JSON
        }

Thank you.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.