Home > Articles > Programming > Windows Programming

Building REST Services Using ASP.NET MVC Framework

This chapter introduces the ASP.NET MVC framework and shows how you can create classes based on ActionResult to handle RESTful actions and responses.
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.

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.

Figure 7.1

Figure 7.1 Original model-view-controller pattern

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:

routes.MapRoute(
    "Default",
    "{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = "" }
);

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:

routes.MapRoute(
    "VariableURI",
    "{MyController}/{*contentUri}",
    new { controller = "MyController", action = "ServiceRequest" }
);

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:

public abstract class ActionResult
{
    protected ActionResult();

    public abstract void ExecuteResult(ControllerContext context);
}

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:

public ActionResult Index()
{
    switch (this.HttpContext.Request.HttpMethod.ToLower())
    {
        case "head":
            // Do HTTP HEAD
            return DispatchHead();

        case "get":
            // Do HTTP GET
            return DispatchGet();

        case "put":
            // Do HTTP PUT
            return DispatchPut();

        case "post":
            // Do HTTP POST
            return DispatchPost();

        case "delete":
            // Do HTTP Delete
            return DispatchDelete();

        default:
            // Unknown method, process error
            break;
    }

    // Process error
    DispatchErrorMethodNotAllowed();
}

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:

// HTTP HEAD?
public ActionResult Index()
{
    ...
}

// HTTP GET?
public ActionResult Index()
{
    ...
}
...
// HTTP DELETE?
public ActionResult Index()
{
    ...
}

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:

// HTTP HEAD
[AcceptVerbs("HEAD")]
[ActionName("Index")]
public ActionResult ProcessHead()
{
    ...
}

// HTTP GET
[AcceptVerbs("GET")]
[ActionName("Index")]
public ActionResult ProcessGet()
{
    ...
}
...
// HTTP DELETE
[AcceptVerbs("DELETE")]
[ActionName("Index")]
public ActionResult ProcessDelete()
{
    ...
}

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.

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:

public class HomeController : Controller
{
    ...
    public ActionResult About()
    {
        ViewData["Title"] = "About Page";

        return View();
    }
}

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:

public class MyController : Controller
{
    ...
    [Authorize]
    public ActionResult DoSomething()
    {
        ...
    }
}

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020