An overview of MVC 5 and Web API

Some general notes on MVC5 and WebAPI…

 

The MVC pattern is been in computer science since 1979, known then as the Thing-Model-View-Editor.

  • The Model: A set of classes that describes the data you’re working with as well as the business rules for how the data can be changed and manipulated
  • The View: Defines how the application’s UI will be displayed
  • The Controller: A set of classes that handles communication from the user, overall application flow, and application-specific logic

MVC has become more popular in web development with this definition

  • Models: These are the classes that represent the domain you are interested in. These domain objects often encapsulate data stored in a database as well as code that manipulates the data and enforces domain-specific business logic. With ASP.NET MVC, this is most likely a Data Access Layer of some kind, using a tool like Entity Framework or NHibernate combined with custom code containing domain-specific logic.
  • View: This is a template to dynamically generate HTML. We cover more on that in Chapter 3 when we dig into views.
  • Controller: This is a special class that manages the relationship between the View and the Model. It responds to user input, talks to the Model, and decides which view to render (if any). In ASP.NET MVC, this class is conventionally denoted by the suffix Controller.

 

ASP.NET MVC 1 released in 2009. There has been 5 major releases in 5 years…

 

Web API 1 released with MVC 4, and have some similar features as web MVC:

  • Routing: ASP.NET Web API uses the same routing system for mapping URLs to controller actions. It contextualizes the routing to HTTP services by mapping HTTP verbs to actions by convention, which both makes the code easier to read and encourages following RESTful service design.
  • Model binding and validation: Just as MVC simplifies the process of mapping input values (form fields, cookies, URL parameters, and so on) to model values, Web API automatically maps HTTP request values to models. The binding system is extensible and includes the same attribute-based validation that you use in MVC model binding.
  • Filters: MVC uses filters (discussed in Chapter 15) to allow for adding behaviors to actions via attributes. For instance, adding an [Authorize] attribute to an MVC action will prohibit anonymous access, automatically redirecting to the login page. Web API also supports some of the standard MVC filters (like a service-optimized [Authorize] attribute) and custom filters.
  • Scaffolding: You add new Web API controllers using the same dialog used to add an MVC controller (as described later this chapter). You have the option to use the Add Controller dialog to quickly scaffold a Web API controller based on an Entity Framework–based model type.
  • Easy unit testability: Much like MVC, Web API is built around the concepts of dependency injection and avoiding the use of global state.

 

Web API also adds some new concepts and features specific to HTTP service development:

  • HTTP programming model: The Web API development experience is optimized for working with HTTP requests and responses. There’s a strongly typed HTTP object model, HTTP status codes and headers are easily accessible, and so on.
  • Action dispatching based on HTTP verbs: In MVC the dispatching of action methods is based on their names. In Web API, methods can be automatically dispatched based on the HTTP verb. So, for example, a GET request would be automatically dispatched to a controller action named GetItem.
  • Content negotiation: HTTP has long supported a system of content negotiation, in which browsers (and other HTTP clients) indicate their response format preferences, and the server responds with the highest preferred format that it can support. This means that your controller can supply XML, JSON, and other formats (you can add your own), responding to whichever the client most prefers. This allows you to add support for new formats without having to change any of your controller code.
  • Code-based configuration: Service configuration can be complex. Unlike WCF’s verbose and complex configuration file approach, Web API is configured entirely via code.

 

Both MVC and Web API uses a naming convention for files and folders. Also, the template project directory structure must follow as such:

Directory Purpose
/Controllers Where you put Controller classes that handle URL requests
/Models Where you put classes that represent and manipulate data and business objects
/Views Where you put UI template files that are responsible for rendering output, such as HTML
/Scripts Where you put JavaScript library files and scripts (.js)
/fonts The Bootstrap template system includes some custom web fonts, which are placed in this directory
/Content Where you put CSS, images, and other site content, other than scripts
/App_Data Where you store data files you want to read/write
/App_Start Where you put configuration code for features like Routing, bundling, and Web API

 

The convention over configuration concept was made popular by Ruby on Rails a few years back, and essentially means:

“We know, by now, how to build a web application. Let’s roll that experience into the framework so we don’t have to configure absolutely everything again.”

 

 

Here are some other notes in regards to the new ASP.NET Identity:

  • One ASP.NET Identity system: In support of the One ASP.NET focus we discussed earlier, the new ASP.NET Identity was designed to work across the ASP.NET family (MVC, Web Forms, Web Pages, Web API, SignalR, and hybrid applications using any combination).
  • Control over user profile data: Although it’s a frequently used application for storing additional, custom information about your users, the ASP.NET Membership system made doing it very difficult. ASP.NET Identity makes storing additional user information (for example, account numbers, social media information, and contact address) as easily as adding properties to the model class that represents the user.
  • Control over persistence: By default, all user information is stored using Entity Framework Code First. This gives you both the simplicity and control you’re used to with Entity Framework Code First. However, you can plug in any other persistence mechanism you want, including other ORMs, databases, your own custom web services, and so on.
  • Testability: The ASP.NET Identity API was designed using interfaces. These allow you to write unit tests for your user-related application code.
  • Claims Based: Although ASP.NET Identity continues to offer support for user roles, it also supports claims-based authentication. Claims are a lot more expressive than roles, so this gives you a lot more power and flexibility. Whereas role membership is a simple Boolean value (a user either is or isn’t in the Administrator role), a user claim can carry rich information, such as a user’s membership level or identity specifics.
  • Login providers: Rather than just focusing on username / password authentication, ASP.NET Identity understands that users often are authenticated through social providers (for example, Microsoft Account, Facebook, or Twitter) and Windows Azure Active Directory.
  • NuGet distribution: ASP.NET Identity is installed in your applications as a NuGet package. This means you can install it separately, as well as upgrade to newer releases with the simplicity of updating a single NuGet package.

 

 

Using Action Results over HttpContext

Most of ASP.NET core uses IHttpModule and IHttpHandler interfaces, and the HTtpContext hierarchy (HttpRequest, HttpResponse). There is no way to replace their functionality, which makes testing any interactions with them very difficult (although not impossible). .NET 3.5 SP1 introduced an assembly named System.Web.Abstractions.dll, which created abstract class versions of these classes (HttpContextBase is the abstract version of HttpContext). Everything in MVC is written against these abstract classes instead of their original counterparts, and it makes testing code that interacts with these classes much easier.
ASP.NET Web API also supports action results with a system that resembles MVC. Although Web API’s dependence on the new abstractions in System.Net.Http.dll means you can effortlessly write easy-to-test controllers, correctly creating the request and response objects is still difficult. Action results in Web API (that is, anything that implements System.Web.Http.IHttpActionResult) isolate the manipulation of request and response objects, and leave developers to write much simpler unit tests for their controllers. Web API’s ApiController base class has dozens of methods to create action result classes written by the ASP.NET team.