Working with optional body parameters in ASP.NET Core 2.2
Working with optional body parameters in ASP.NET Core 2.2

Working with optional body parameters in ASP.NET Core 2.2 is now possible and I will show how to solve the issue in this post. Optional parameter exists in .Net for a long time. Specifying the default value used to be enough to mark them as optional. However, marking a body parameter in a Web API action method is not going to work if you are working with .NET Core 2, 2.1 and 2.2 versions.

Let me explain the problem that you might face and a solution to solve the problem.

An issue in accepting body parameter as optional

I have a model class in my action method and that reads the content from the body as shown below.

        // POST api/values
        [HttpPost]
        public IActionResult Post([FromBody]ModelClass request = null)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            return Ok();
        }

Here is the problem, as soon as you include an attribute [FromBody], MVC binding will trigger. If you did not send content in the request body, you will see an error as shown below.

{
  "": [
    "A non-empty request body is required."
  ]
}

This is an existing issue in .NET Core 2.0. Optional body parameters no longer work since upgrading to .NET Core 2.0 #6920

Solution

One of the solutions is to read the content from the request body and then process it if it was sent in the request.

 string body;
            SomeClassModel model = null;
            using (var reader = new StreamReader(Request.Body, Encoding.UTF8, true, 1024, true))
            {
                body = reader.ReadToEnd();
            }

            if (!string.IsNullOrEmpty(body))
            {
               finalModel = JsonConvert.DeserializeObject(body);
            }

This way the body parameters can be made optional and custom validation can be implemented in case you need to validate a JSON string in the body parameter.

Related Posts

Implement create, read, update, and delete functionalities using Entity Framework Core

Conclusion

In this post, I showed how to work with optional body parameters in ASP.NET Core 2.2. That’s all from this post. If you have any questions or just want to chat with me, feel free to leave a comment below.

Leave a Reply

Your email address will not be published. Required fields are marked *

Verified by MonsterInsights