This chapter is from the book

This chapter is from the book

In Chapter 6 we created a basic RESTful service using bare-bones ASP.NET techniques such as implementing an HTTP handler that represents our service. Interestingly, this isn’t far from what happens with the ASP.NET MVC framework, but we don’t look at it quite that way. Moreover, we gain some niceties revolving around URL routing and controller action invocations.

The ASP.NET MVC Framework

In mid-2007 or so, Microsoft introduced a new way to build ASP.NET applications that is based on the classic model-view-controller (MVC) design pattern. Although we could argue whether it fits the true MVC pattern or the more contemporary front controller pattern, the idea is that the traditional Web Forms method of creating Web pages is replaced by a framework that is actually based on RESTful principles. If you’ve not tried the ASP.NET MVC framework, it is available for download from this URL: http://www.asp.net/mvc

Traditional Web pages are rooted in disk files, and the representation they offer is the rendered HTML that comes from either the HTML stored in the file or, in the case of ASP.NET, the page offered up by the ASP.NET PageHandlerFactory. Consider what happens when you enter a URI such as the following:

http://www.contoso.com/Default.aspx

Here, ASP.NET receives the incoming request and shuttles it to the PageHandlerFactory. PageHandlerFactory’s job is to locate the compiled code that represents the requested page. This code, based on IHttpHandler, then passes through a series of what amounts to workflow steps to render the HTML that is ultimately returned to the client. In the end, though, whether the client requests an HTML page or an ASP.NET page, the URI they use targets a resource that (typically) resides in a specific file on disk. And if you’re using PageHandlerFactory, the representation the client will receive is HTML or some dialect of HTML, like XHTML.

The ASP.NET Web Forms model uses two files most of the time. The first file is a markup file that contains basic HTML and ASP.NET-specific markup that indicates which controls the page handler will instantiate and otherwise manipulate. The second file is called the “code-behind” file (or sometimes “code-beside”), and it contains programming logic in your choice of .NET language. As far as it goes, this page mechanism is fine and it works. But there is a tight coupling that exists between the markup and the logic that drives the page since the markup and code-behind pages are closely related. This doesn’t separate the view from the logic behind the view, which causes difficulties when considering such things as automated unit testing or test-driven design, or even when trying to inject standard practices like separation of concerns. Although much can be done by developers to mitigate this tight coupling, in practice most development teams don’t (or can’t) make the investment because it is not self-evident, and it requires planning, training, and code review to ensure consistent implementation. Ironically, these techniques involve separating the data, the user interface, and the manipulation of that user interface—which in itself is a form of MVC.

Moreover, ASP.NET had received negative comments from time to time from some in the developer community due to the way the Web Forms page is rendered. These developers consider the Web Forms page rendering process to be “heavy,” meaning it takes too long and requires too much server resource to render a simple page. Authoring and rendering ASP.NET controls isn’t a simple process either, and at times scalability can be impacted. In addition, the Web Forms model is inherently stateful, using information caches such as view state, control state, and even the easy-to-access session state. It’s entirely too easy to get yourself into trouble when implementing a Web site with more complexity than simple content pages.

NOTE

It isn’t my intention to argue the merits or demerits of either ASP.NET platform here. In my opinion both Web Forms and ASP.NET MVC are good and have beneficial uses. To me it’s more a matter of selecting the proper tool for the job. Web Forms are more resource-centric whereas ASP.NET MVC is more action-centric. Web Forms give you some programming niceties, because view state isn’t necessarily a bad thing at times, whereas ASP.NET MVC allows you to program “closer to the metal.”

I also found the MVC framework to be a wonderfully RESTful platform, but I understand Microsoft doesn’t necessarily agree with this sentiment, preferring for developers to instead use Windows Communication Foundation services. The ASP.NET MVC framework is a terrific platform on which to build RESTful solutions using the very constructs the framework itself provides, but I also understand Microsoft’s position. In practice, I think you should decide for yourself based on your application’s requirements. I wouldn’t hesitate to create a RESTful solution based on ASP.NET MVC if that best fit my application’s needs.

The ASP.NET MVC framework was created to address these issues, and you can download the framework as well as learn much more about it at http://asp.net/mvc. The ASP.NET MVC framework is built using a modified version of the venerable model-view-controller pattern, the original concept for which is shown in Figure 7.1. Although you won’t find this figure in the original source material, the idea Figure 7.1 embodies comes from the original source, which you can find at http://heim.ifi.uio.no/~trygver/1979/mvc-1/1979-05-MVC.pdf. I used the word “modified” only because when creating a new ASP.NET MVC project, you’re given sample views and controllers. However, any model creation is up to you, so implementing the feedback to the view is therefore also up to you to implement should you choose to do so.

If you’re wondering about the feedback line on the right side of the diagram (as I was for a long time), it comes from the definition of the view in the aforementioned reference. Other patterns, like the model-view-presenter (and more contemporary patterns based on MVC, like the front controller pattern of which the ASP.NET MVC framework is built around) often seek to address things such as this direct model-view feedback or provide for other pattern optimizations.

The model-view-controller pattern was revolutionary in the sense that it clearly separated the user interface–specific rendering (the view) from the logic that drives what is shown. User actions, such as button clicks, are passed from the view to the controller, which will either create a new model-view-controller set (such as when redirecting to a different Web page) or interact with the model, which is where both the application logic and the data access reside.

The ASP.NET MVC framework relies on the UrlRoutingModule to shuttle Web server requests to the MvcHttpHandler, which then interprets the requested URL and activates the appropriate controller. Controller activation is therefore ultimately based on the URI, and a controller action (method) is activated instead of directly targeting a disk-based resource. At its very core, the ASP.NET MVC framework is based on RESTful principles!

In fact, think back to the preceding chapter. Remember the virtual nature of the service I created? The BlogService didn’t actually exist as a .aspx or .ashx file but rather was created and registered through the use of UriTemplateTable. By adding items to the UriTemplateTable and then later checking the incoming URI against the preregistered URIs the service would accept, the service could discern valid URIs, at least from the service’s point of view. It could then also dispatch the processing of those URIs along with matched information, such as the parsed blogID.

This is very similar to the mechanisms I just described when looking at the ASP.NET MVC framework. The framework provides a more programmer-friendly and standardized way to execute your own code (the BlogService is fully custom, after all), but the process for accessing resources is very, very similar in both cases. Let’s now look at some MVC framework details.

URL Routing

The URL routing module is driven by “mapped routes,” which are URIs you specify and couple to a specific controller. This process is much like setting up the UriTemplateTable in the preceding chapter. Here is the route map for the default route when you create a brand-new MVC Web application:

Default is the name of the route, and you can imagine that this is used as a key in a route table (undoubtedly a dictionary object). The value {controller}/{action}/{id} is the “designed” URI, which essentially says this mapped URL will be activated like so:

http://servername/virtualdirectory/controller/action/id

If no controller is specified, it will default to HomeController. The MVC framework will take the value placed in the route map, Home, and automatically concatenate the word Controller to look up the appropriate controller class in the Controllers folder, which in this case is HomeController. If no action is specified, the MVC framework will examine the HomeController class for a method named Index. However, if the URI

http://servername/virtualdirectory/Home/About

is used, then the MVC framework will invoke the About method contained within the HomeController.

In both sample URLs there was no id value. None was specified in the URL, and the Index and About methods contained within the HomeController have no parameters to deal with it since none is expected for those actions. However, if you created a blog and provided an action that listed pages in your blog, the id value could become the page number:

public ActionResult Page(Int32 id)
{
...
}

In this case, the URL for page 3 of your blog would be this:

http://servername/virtualdirectory/Home/Page/3

The HomeController’s Page method would be invoked and passed the value 3 as the id parameter. You’d then process the page number using whatever logic makes sense for locating and displaying the desired view.

There is a special case this chapter’s service takes advantage of when it registers the RESTful service URI with the URL routing framework, and that is the parameter wildcard. If your application has the specific pattern the default route maps for you, which is controller, action, and then ID, the default route works fine. But if your application might have a URI that varies, you could map your route using the wildcard and decide what to do when your controller is invoked. Here’s an example:

This URI is registered using the VariableURI name, but it can be activated using an infinite number of URIs, all of which map to MyController’s ServiceRequest action method. The remainder of the URI is provided to the ServiceRequest method as a string parameter. You’d use this if you simply can’t define the URI for all possible client invocations or your URI will vary. Later in the chapter I’ll show you how to register a new route in the route map.

Controller Actions

Note that the Page method shown previously returns something known as an ActionResult. You might imagine an ActionResult returning some rendered HTML value, but in fact an ActionResult is simply an abstract class defined as such:

Several concrete ActionResult classes are shipped with the ASP.NET MVC framework, including ViewResult, which is returned from the controller’s View method (I’ll discuss this in a bit more detail in a following section), RedirectToRouteResult, and PartialViewResult. Of course, nothing says you can’t create your own, and I did exactly that when creating the RESTful service for this chapter. (And of the six cases the service handles, only one of those cases returns HTML to the client.)

As I alluded to earlier in the chapter, URIs are mapped to controller actions (not disk files as with traditional ASP.NET). Controller actions are implemented by methods hosted by your controller classes that return ActionResult values. The behavior of the controller action in most cases would be to spin up a .aspx page (the view), but though this is common, it isn’t required. Your controller can take other actions, depending on your application’s needs.

Accepting HTTP Methods

A nice feature of the ASP.NET MVC framework is the capability to separate controller actions based on HTTP method. That is, you can specify one controller action for HTTP GET and another for POST, PUT, DELETE, or whatever. Coupled with this concept is the capability to overload the naming of the methods from the framework’s point of view. This is a great feature for RESTful services in which you generally support more than HTTP GET.

Let’s look at an example. Here is a valid URI for this chapter’s sample service, CodeXRC:

https://servername/virtualdirectory/CodeXRC

You can imagine CodeXRC as a simple-minded source code repository. If a client accessed this URI, to determine what to do, you would need to examine the HTTP method. If it was HEAD, you would do one thing. If it was GET or POST, you would do another. To accomplish this, you would probably write code that used a switch statement using the HTTP Method to decide what to do:

In fact, this is precisely what you saw in the preceding chapter. It’s another example of a dispatch table in which the appropriate service handler is invoked based on HTTP method. It’s also very much “boilerplate” code that could be rolled into a framework, and that’s exactly what was done in ASP.NET MVC.

But then we have an issue. We can’t have identically named methods with identical method signatures. If the framework can route actions to a controller based on HTTP method, then there has to be some way to overload the name of the method so that we don’t have syntactical errors. That is, we can’t have this situation:

Clearly this won’t compile, but this is exactly the situation we would have since a single URI serves all HTTP methods (keeping the original service URL in mind: https://servername/virtualdirectory/CodeXRC).

It’s for this reason the ASP.NET MVC framework coupled the ability to handle different HTTP methods with different controller actions using an aliased name. The AcceptVerbs and ActionName attributes cleanly disambiguate the HTTP method and aliased name:

In this case I’ve rewritten the previous example to show the proper technique. From a URI perspective, the controller action is always Index. But the true controller action to be invoked will depend on the HTTP method used to invoke the action. If the HTTP GET method is used, the ProcessGet action is invoked, and so forth.

This chapter’s sample RESTful service makes heavy use of this new feature, and I’d expect that many services will do so over time as well.

Views

Although this book isn’t about building Web sites using ASP.NET MVC, I thought a paragraph or two that describes how the views are handled is appropriate since I’m introducing the framework.

NOTE

You’ll find that I didn’t make use of the view capability in the chapter’s sample application. Perhaps I should have. I certainly could have. I just found it more convenient to take the notion of a controller “action” literally and have the controller address the service request. The point was not to render a “view” but to respond to a call for action, even if that action results in rendered HTML. Had I been building Web pages, I would have done things differently. (If you disagree with my implementation, that’s fine. When you build your own services, by all means follow your own interpretation of the pattern.)

The ASP.NET MVC framework uses a folder (conventionally) named Views to contain all the views, with views associated with a particular controller in a subfolder named after the controller. Views associated with the HomeController, for example, are found in the Home folder, which is a child folder of Views in the main application directory. If all you ever do is invoke the view associated with the action, the MVC framework will automatically select the view named for the action. For example, the default HomeController has an About action that invokes the About view in the Home folder of the Views Web application directory. This code does that job, with the MVC framework’s help:

The About action returns a ViewResult from the controller’s base View method, which implements the algorithm I mentioned for locating the default view for the action. And as you recall, ViewResult is derived from ActionResult.

However, you might want to use another view, and as it happens the controller’s base View method is overloaded, allowing you to select other views based on name. One I find myself using a lot is this overloaded version:

protected internal ViewResult View(string viewName, object model);

With this overloaded version, you provide the name of the view you would rather invoke as well as some page-specific data the view can access through its ViewData property (specifically ViewData.Model). Perhaps you have one view that’s based on a data grid and another based on a chart. Using this overloaded View method, you can select the most appropriate view based on your application’s needs.

You also can redirect to another page entirely. The simplest way is to use the controller’s Redirect method, which returns a RedirectAction object. But other redirect methods exist, such as RedirectToAction and RedirectToRoute. Of course, these allow you to redirect to a different controller action or mapped route.

The Model

In MVC terms, the model is where you place your data access layer and any application-specific business logic. When you create a brand-new ASP.NET MVC Web application, the project wizard creates controllers and views for you as starter code. But no model is created—only a subdirectory is created for you within which you place model code. Nearly all the CodeXRC service functionality is implemented in classes that are housed in the model folder, and you’ll find this is typical for MVC-style applications.

ASP.NET MVC Security

ASP.NET MVC incorporates the notion of an Authorize attribute and the AccountController class. Imagine a controller that looks something like this:

The Authorize attribute causes the ASP.NET MVC handler to look for a controller named AccountController and invokes its Login action. The Login action, and the AccountController for that matter, are designed to work with the ASP.NET Forms Authentication module. Therefore, Login and Register generate an authentication cookie, Logout destroys the cookie, and everything else the account controller does favors the Forms authentication process in ASP.NET.

After seeing the additional work ASP.NET MVC offered, which was to wrap access to the Forms authentication services (or at least a couple of them) behind a custom interface, I thought it would be useful to try to work the HTTP Basic Authentication module from the preceding chapter into the MVC framework. But the simple truth is that given the module from the preceding chapter, the entire concept behind the AccountController, or at least the Forms authentication parts of it, aren’t needed.

With Forms authentication, navigating between secured pages is accomplished using the ASP.NET security cookie. The Forms Authentication module looks for the cookie, and if it’s present and valid when accessing secured resources, the Forms Authentication module allows the secured page to render. The Authorize attribute controls which actions are secured.

HTTP Basic Authentication, however, doesn’t use a cookie. In fact, this is what makes it so appealing to RESTful services. The client needs to cache the credentials and offer them to the Web server each time access to a secured resource is desired. Modern Web browsers all do this for you, and most (if not all) of the sample desktop applications in this book will also cache the credentials for you if you choose so that each service access doesn’t force reauthentication.

In the end, I simply copied the module from the preceding chapter into this chapter’s sample application, changed the namespaces involved, and made the necessary adjustments to the web.config file, and the HTTP Basic Authentication worked tremendously well. Since I didn’t require the AccountController, I deleted it and the views associated with it, knowing that the browser itself would query me for my credentials—I don’t need a “login” page for that. True, I also then dismissed the registration and password change request pages, but there is some merit for brevity when producing chapter samples.

NOTE

I also can’t use the spectacular Authorize attribute, but I found I didn’t need it with the custom authentication module. If I were producing a traditional MVC Web application, one based on views, I’d embrace these new ASP.NET MVC tools—the account controller and security attribute—but for a truly RESTful service that requires HTTP Basic Authentication, I discovered they’re just not the right tools for the job.