Defining a Model

Chapter 17 presented the ASP.NET MVC application. Recall that, in this pattern, there is a Model that represents your business objects and their persistence layer. The Controller is used to manage requests and response from the HTTP traffic to your site. Views, of course, allow you to render a user interface (UI) to the user. The ASP.NET Web API service model leverages this same pattern. You define models for your data and a controller for handling service requests and response. (There is no real UI, of course, and hence no views.)

The framework for the ASP.NET Web API handles the plumbing of turning your model objects into serialized data that can be embedded in the HTTP response message. This serialization is typically JSON or XML but can be other formats, too. In this way, clients that can make a basic HTTP GET or POST request and read the response as JSON, XML, or a related format can work with your service. In fact, a client call may indicate which format it needs (called content negotiation) as part of the Accept header in the HTTP request.

For example, let’s work to create a set of services for managing customer objects. To get started, we will create a simple class to represent our model: in this case, a customer. To do so, we start with the ASP.NET 5 Web API template project called WebApiService and follow these basic steps:

1. Add a folder named Models to the project in Solution Explorer.

2. Add a class to the Models folder and name the class Customer.

3. Write a using statement at the top of Customer for System.ComponentModel.DataAnnotations.

4. Write simple properties to represent the customer.

5. Add data annotations to add field level validation.

Listing 19.1 shows an example of this simple Customer model class. Notice that this is similar to the model created back in Chapter 17. Next, we will use this model to create HTTP services.

LISTING 19.1 The Customer.cs Model Class


using System;
using System.ComponentModel.DataAnnotations;

namespace WebApiService.Models
{
  public class Customer
  {
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }

    [Required, EmailAddress]
    public string Email { get; set; }

    public bool OptInEmail { get; set; }

    public string Notes { get; set; }
  }
}


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset