locked
ASP.NET Web API 2 - Validation RRS feed

  • Question

  • User-1502889591 posted

    How would you check when using a [FromBody] User user in a [HttpPost] method, if the JSON-Object has more keys than needed for the User.

    Take in mind that the ModelState is being validated and all properties from User are [Required].

    In result i don't want it to be possible for the client to send a JSON-Object to this endpoint which has more keys than a User-Object has properties.

    Friday, April 26, 2019 8:33 AM

All replies

  • User475983607 posted

    Users can send anything to a Web API end point.  Can you post code that illustrates the problem you are trying to solve?

    Friday, April 26, 2019 11:02 AM
  • User753101303 posted

    Hi,

    It will be just ignored but if you want it seems you are looking for something such as https://www.newtonsoft.com/jsonschema

    Maybe a custom attribute that would add a schema validation step (or you want to provide a schema to 3rd party developers so that they can self check if needed if the json they generate is what your API expect ?)

    Friday, April 26, 2019 11:14 AM
  • User-1502889591 posted

    Well i got a solution now:

    By adding a custom filter to the method like this:

            [ValidateUserModelAttribute]
            public HttpResponseMessage CreateUser([FromBody]User user)
            {

    And creating the filter:

    public class ValidateUserModelAttribute : ActionFilterAttribute
        {
            public override void OnActionExecuting(HttpActionContext actionContext)
            {
                // Read request via stream:
                string request;
                using (var stream = new StreamReader(actionContext.Request.Content.ReadAsStreamAsync().Result))
                {
                    stream.BaseStream.Position = 0;
                    request = stream.ReadToEnd();
                }
    
                // Convert request to JSON-Object:
                JObject jsonObject = (JObject)JsonConvert.DeserializeObject(request);
    
                // Number of properties from request:
                int numberOfRequestProperties = jsonObject.Count;
    
                // Number of proeprties the request should have:
                int numberOfModelProperties = typeof(User).GetProperties().Length;
    
                if (numberOfRequestProperties != numberOfModelProperties)
                {
                    string message = string.Format("There should be {0} key/value pairs in your json request. But there are {1}",
                        numberOfModelProperties, numberOfRequestProperties);
    
                    actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, message);
                }
            }
        }

    Additional you can check for duplcate keys if you insert this into the code:

                // Return bad request message if there are duplicate keys:
                try
                {
                    // Set JsonReaderException to be thrown via .Error if there are duplicate keys:
                    var jsonLoadSettings = new JsonLoadSettings { DuplicatePropertyNameHandling = DuplicatePropertyNameHandling.Error };
    
                    // This throws a JsonReaderExpection due to the settings if there is a duplicate key:
                    JConstructor.Parse(request, jsonLoadSettings);
                }
                catch (JsonReaderException e)
                {
                    string message = string.Format("Duplicate key found: {0}", e.Message);
    
                    actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, message);
                }

    Friday, April 26, 2019 12:51 PM
  • User-1038772411 posted

    You Can Refer Microsoft Official site for more and Pure problem solving technique.

    https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/model-validation-in-aspnet-web-api

    Thanks.

    Monday, April 29, 2019 6:07 AM