14 JSON serialization / deserialization and custom model binding

 

This chapter covers

  • Serializing and deserializing JSON data
  • Using the [FromBody] argument attribute to magically deserialize JSON data
  • Implementing a custom model binder using the IModelBinder interface
  • Generating an OpenAPI specification on-the-fly at runtime

This is it. The last refactoring chapter. Throughout this book, you refactored an existing code base from the ground up. We learned about test-driven development, how to write clean code, and tips and tricks for C#.

Figure 14.1 In the previous chapters we implemented the database access, repository, service layers, and FlightController class. In this chapter, we finish the job and implement the BookingController class.

In this chapter, we implement the last controller: BookingController (section 14.1). After that, we do some manual testing and acceptance testing against the OpenAPI specification from FlyTomorrow. We also set up Swagger middleware to generate an OpenAPI specification on-the-fly (section 14.2). This is optional, but a very useful technique to know as Swagger helps us with our acceptance testing.

14.1  Implementing the BookingController class

14.1.1    Introduction to data deserialization

14.1.2    Using the [FromBody] attribute to deserialize incoming HTTP data

14.1.3    Using a custom Model Binder and Method Attribute for model binding

14.1.4    Implementing the CreateBooking endpoint method logic

14.2  Acceptance Testing and Swagger middleware

14.2.1    Manual acceptance testing with an OpenAPI specification

14.2.2    Generating an OpenAPI specification at runtime

14.3  The end of the road

14.4  Summary