Tag Archives: ASP.NET tutorial

Dependency Resolution and Hosting: Dependency Injection

There’s a sense in which the entire idea behind having consumable services such as the ASP.NET Web API provides is a decoupled, reusable architecture. You want to have a body of data and business logic decoupled from a client application so it can be used by a variety of client applications. Testability is also an important architectural issue. A unit of code must be decoupled from its dependencies in order to write automated tests against it.

Practices like Test Driven Development (TDD) virtually force writing code this way. In software development, all code should be written with these principles in mind, including our client applications and the services, themselves.

Dependency Injection is one way to help achieve decoupling, reusability, and testability in Web API services. With this in mind, the Web API framework was designed to facilitate this technique.

Inversion of Control

In a broad sense, Inversion of Control is the concept of allowing something outside of a system to control it. In other words, the system doesn’t run itself but something or someone on the outside invokes it when it is needed. In a very broad sense, things like a web-based interface over a database could be an example of Inversion of Control. In object-oriented software development, Inversion of Control means that, instead of tightly coupling objects to other objects in code, objects are pulled together at runtime by some outside mechanism.

If you go to a pizza restaurant, you’ll see people making pizzas. What you probably won’t see are people growing tomatoes for the sauce, milking cows to make the cheese, or processing cardboard to make the pizza boxes. The pizza shop needs all those things, but they are not responsible for creating them. Someone else creates them and gives them to the pizza shop to use to get their job done. This is roughly analogous to Inversion of Control in software development.

For instance, if you are writing a repository class that will save products to the database, it will need some kind of data access object to perform the database operations. One way to do this is simply to instantiate a data access object in your repository code. However, this will tightly couple your repository code to that data access object.

With Inversion of Control, you code the repository to an abstraction (usually an interface) that represents the data access object and you rely on some outside mechanism to instantiate a data access object and give it to your repository at runtime. By doing this, your repository is now decoupled from any particular data access object. This allows you to reuse the repository code with various data access components as well as making it testable (by giving the repository a “mock” data access object).

There are various techniques that give you Inversion of Control in software development and one of the more common and prominent ones is Dependency Injection.

Using Dependency Injection

Many classes that you write need other objects to do their jobs, and nowhere is this more true than in a services layer. Many services need objects to access data, process business rules, perform validation, handle logging, and a wide array of functionality that the services layer tends to coordinate.

With Dependency Injection, programmers code their classes assuming that these objects will be instantiated from an entity outside their class and passed into it. Sometimes, this is done by exposing properties that can be set from the outside. A very common way to set up for Dependency Injection, however, is to handle it in the constructor.

In the previous example, there is a Logger class that needs a file writer object. In tightly-coupled code, the Logger would just instantiate its own file writer:

However, this would bind the Logger class to a specific FileWriter object. By allowing an object that implements IFileWriter to be passed into the constructor, you can now reuse this class for various kinds of file writers. Also, this code is very testable because you can pass in a fake file writer for testing purposes—perhaps one that writes to a test file or even does nothing at all.

If code is written to receive its dependencies from the outside, these objects have to come from somewhere. Something on the outside needs to instantiate these objects and pass them into the objects that require them. Some mechanism needs to inject these dependencies. There’s more than one way to do this, but this is such a common issue in software development that common libraries have been written to solve this problem. They are often called IoC (Inversion of Control) Containers or DI (Dependency Injection) frameworks.

This post is an excerpt from the online courseware for our ASP.NET Web API Hosting and Dependency Resolution course written by expert Philip Ledgerwood.

ldn-pledgerwoodPhilip Ledgerwood has been a software developer for fifteen years. He currently works primarily in .NET technologies producing custom software for organizations of all sizes. He has also done extensive training for those same organizations in both technical and business process topics.

Requesting Other MIME Types

MIME originally stood for Multipurpose Internet Mail Extensions to refer to the fact that emails would sometimes carry data that wasn’t text, such as attached graphics or spreadsheets. MIME types were a way for email clients to recognize the different types of data coming across and handle them appropriately.

When dealing with web applications today, MIME types (also referred to as Content-Types) refer to all kinds of data that web clients access over the Internet. A common MIME type is text/html, but there’s also text/css, application/xml, and even non-textual types such as application/pdf or image/gif.

JSON is the default MIME type that Web API services return, and it might fit a great many needs for web services, but what if your application needs to get XML from a service, or a comma-delimited file, or even a graphic or a spreadsheet?

XML

XML is an extremely common data exchange format for web services and, as such, the Web API can support returning XML data with no code changes. All that needs to happen is that the HTTP request has to specify a Content-Type of application/xml.

If a Web API service gets an HTTP request with a Content-Type of application/xml, it will automatically serialize and return data as XML rather than JSON. Nothing special needs to be done to make this happen unless you want to provide a different XML serializer.

NOTE: At the time of this writing, the ASP.NET Web API uses the DataContractSerializer in the .NET Framework behind the scenes to do XML serialization. You can set a different serializer in the Web API’s configuration.

Other MIME Types

JSON and XML are the only MIME types the Web API handles out of the box. However, the Web API can send back virtually any MIME type out there. If you want a Web API service to return something besides JSON or XML, you must first write your own “serializer” for the data you want to return. In Web API parlance, this is called a Media Formatter. This Media Formatter needs to be registered in the Web API configuration. Once this is done, any requests for that data that have a Content-Type of the MIME type of the appropriate Media Formatter will receive that type of data back from the service.

ldn-pledgerwoodThis post is an excerpt from the online courseware for our ASP.NET Web API Model Binding and Media Formats course written by expert Philip Ledgerwood.

Philip Ledgerwood has been a software developer for fifteen years. He currently works primarily in .NET technologies producing custom software for organizations of all sizes. He has also done extensive training for those same organizations in both technical and business process topics.

Model Binding: HTML Templates

url4

 

The client-side migration revolution has not left markup untouched. Given thatclients making service calls and rendering the results has become such a common way for web applications to work with data, especially as mobile application use is on the rise, a good deal of attention has been given to the rendering aspect of using service data.
The standard way of dealing with data returned via AJAX was to use JavaScript to concatenate the data into strings of HTML and then dynamically write that HTML into the DOM. Although the basic principle is the same, mechanisms have been developed in recent years to make this process easier and more modular. Binding data to HTML templates is a popular way to do this, and using it has even given rise to a pattern commonly called MVVM.

MVVM

MVVM stands for Model-View-ViewModel and describes a client rendering design pattern.

  • The Model represents your actual data, such as might be pulled from a database or a service.
  • The View is the actual UI that renders the ViewModel, which will generally be HTML in the case of typical web application development.
  • The ViewModel is Model data that has been shaped specifically with the goal of binding this to a View that will render the data.

This may not sound all that different from the MVC or MVP patterns, but one of the things that makes the MVVM pattern a little more exciting is that changes to the ViewModel can update the View and the Model immediately.

Let’s consider the traditional client-server way of editing data. If you want to add a new customer in a web application:

  1. Pull up an HTML form and make changes to the form.
  2. >Click Submit so the page posts this data to code that writes it into the database.
  3. The page refreshes with any new information such as Customer Id.

Now let’s consider using MVVM to edit data. With the MVVM pattern, a ViewModel sits between the View (the form) and the Model (the data from the database), which gives you flexibility on when and how these updates happen >and renders the changes in real-time. If you want to add a new customer using MVVM:

  1. Fill out the Add Customer form.
  2. Click Submit, which adds the customer to the ViewModel.
  3. This change automatically updates an Added Customers grid at the bottom of the page with no refresh.

At this point you can decide if you want the new customer to be saved directlyto the database. If you do, then as soon as your server-side code saves the customer and gets the Id, it can put the Id into the ViewModel which automatically updates any UI elements bound to it.

You could also keep the “Added Customers” in the ViewModel but not save any of them until the user clicks the Commit Changes button. This allows theuser to add, update, or delete all kinds of operations on that data with a UI thatresponds immediately to changes but doesn’t commit anything to the database until it’s told to.

The main point is that in MVVM, the ViewModel is directly bound to the View, so any changes to it automatically update the View. This adds a huge level of responsiveness and options when writing web applications. Some applications are referred to as Single-Page Applications because the MVVMpattern enables users to do everything on a single page bound to a modifiable ViewModel.

Binding ViewModels to HTML

Much like AJAX, there are a number of JavaScript libraries that have already been written to help you with the process of binding an HTML UI to a ViewModel. The basic principle behind them all is that you create a snippet of HTML and use attributes or JavaScript functions to mark off the dynamic partsthat will get their data from the ViewModel.

When a web page containing an HTML template is requested, an AJAX operation gets data from a service. This data either directly becomes or is incorporated into a JSON ViewModel, and the JavaScript binds this ViewModel to the corresponding places marked off in your HTML. Any changes to the JSON ViewModel will automatically update the UI pieces that are bound to them.

Like AJAX, there’s nothing stopping you from writing all the code for this process yourself, but a number of libraries exist that already do this. One popular library for binding JSON ViewModels to HTML templates is Knockout.js, and Microsoft includes it by default in Web API projects. There are other options however, such as Pure, Mustache, or JTemplates. Also like AJAX, no Microsoft-specific technologies or platforms are required to use HTML templates. On the client/consumer end of HTTP web services, you are free to use whatever you like, all the way from static HTML to PHP to JSP to anything in between. It’s all HTML and JavaScript at this point.


ldn-pledgerwoodThis post is an excerpt from the online courseware for our
ASP.NET Web API Model Binding and Media Formats course written by expert Philip Ledgerwood.

Philip Ledgerwood has been a software developer for fifteen years. He currently works primarily in .NET technologies producing custom software for organizations of all sizes. He has also done extensive training for those same organizations in both technical and business process topics.

ASP.NET Web API: Server-Side Pipeline

power-sass-multi-device

In a recent article we discussed the client-side of the Web API pipeline. This article takes a look at the server-side!

The server-side of the Web API pipeline is where most developers spend their time as this affects the Web API services, themselves. It opens up somepowerful capabilities for developers of Web API services. Virtually all the default objects in this pipeline are extensible, allowing developers to write their own custom implementations.

WCF developers will find great familiarity, here, because the Web API hooksare very similar to the hooks provided by recent versions of WCF.

Virtually every body of services has cross-cutting concerns that apply across the board and do not easily fit into single-responsibility service calls. As a result, developers often have to duplicate code or end up with service methods that are responsible for several things.

By familiarizing yourself with the server-side pipeline, you’ll have the baseline concepts for adding security to all your services, adding logging, sending custom response data types, and much more.

HttpServer

The HttpServer class derives from HttpMessageHandler. It acts as the in-code representation of the server receiving the HttpRequestMessage. The HttpServer will then send the HttpRequestMessage through a configured chain of HttpMessageHandler objects.

The HttpServer object has even less properties and methods than the HttpClient object. It should truly be thought of as a bare bones sender and receiver as opposed to a container for a large degree of logic. The design of the Web API architecture encourages you to write your custom functionality in >reusable modules that can be hooked up to an HttpServer as opposed to using the actual HttpServer to get that work done.

It also bears repeating that the HttpServer itself will not have much data at all about a current request or a current response. That information is encapsulated in the HttpRequestMessage and the HttpResponseMessage objects, respectively.

HttpMessageHandler Chain

The Web API can be configured to put other classes that derive from HttpMessageHandler in the request processing chain. These handlers can read the request, manipulate it, and send a response or pass the request to the next handler in the chain. This is where most developers add custom code. This code is organized into custom message handlers that are then added to the HttpServer configuration. These handlers become organized in a chain that each request passes through. Handlers can send a response back directly or execute some code and pass the request down to the next link in the chain. This chain can be used to check every request for security keys, log data from them, etc.

The last handler in the chain is always HttpControllerDispatcher. If a handler further up the chain sends a response back to the client, the request will never 13px;”>make it to the controller logic, once again making this the ideal location tocheck for authorization or any other operation you’d like to occur before the controller processes the request. The HttpResponse message is also passed up through this chain ending in the HttpServer which sends out the final response.

HttpControllerDispatcher

The HttpControllerDispatcher handler is always the last in the HttpMessageHandler chain. It takes the URL and the HTTP method from the HttpRequestMessage and routes it to the appropriate Web API controller and action.

Since this is the last HttpMessageHandler, it will not receive any requests that get completely handled and responded to by another HttpMessageHandlerfurther up the chain. This is very useful because, if you have another message handler dealing with the request, you don’t want controller code to process it. If the controller sends a response, the HttpControllerDispatcher will capture the appropriate HttpResponseMessage and send it back up the handler chain.


ldn-pledgerwoodThis post is an excerpt from the online courseware for our
ASP.NET Web API HTTP Pipeline course written by expert Philip Ledgerwood.

Philip Ledgerwood has been a software developer for fifteen years. He currently works primarily in .NET technologies producing custom software for organizations of all sizes. He has also done extensive training for those same organizations in both technical and business process topics.

ASP.NET Web API: Client-Side Pipeline

power-sass-multi-deviceMicrosoft .NET Framework technologies that support a request-response pattern typically use a pipeline, which is a sequence of events that fire to process a request and send back an appropriate response.

Pipelines are important because they allow developers to run code at various stages of processing a request.

The ASP.NET Web API has a pipeline and, by taking advantage of how the API processes HTTP messages, you can easily add some very useful functionality. The Web API has a processing pipeline for both the client and >the server, and this article will focus on the Client-Side Pipeline!

Client-Side Pipeline

The Web API pipeline has two “sides” to it: the client-side and the server-side. Understanding the client-side pipeline is useful as virtually any application can harness the client-side objects to make calls to a Web API. The objects available in the client-side pipeline are especially useful when creating applications that need to access Web API services directly from application code and consume the results.

HttpClient

The HttpClient object represents the client making the request. You can instantiate the object in code, use it to generate an HttpRequestMessage, and send it asynchronously to a URL to be handled by a Web API application. The HttpClient then receives an HttpResponseMessage and handles the contentsaccordingly.

The HttpClient only has four properties, and its methods are primarily concerned with various ways to send an HTTP request and receive a response. The HttpClient is somewhat analogous to AJAX frameworks that essentially facilitate sending requests and receiving responses, leaving it to other code to unpack the response and use the data meaningfully. In the same way, the bulk of the logic dealing with a service response will operate on the HttpResponseMessage object, which will contain the actual data that the requestor needed.

NOTE: With the popularity of various AJAX libraries, many applications will make client-side calls to the Web API directly, but if you have a need to make these calls using server-side code, the HttpClient object will beuseful.

HttpMessageHandler

The HttpMessageHandler object sends the HttpRequestMessage generated by the HttpClient to the right place and listens for an HttpResponseMessage. When a response is received, the HttpMessageHandler is the first object to process it before handing it back to the HttpClient.

HttpMessageHandler is actually a base class for all such handlers. The default implementation for the client-side pipeline is the HttpClientHandler, which satisfies most basic usages of the Web API. However, you are free to write your own implementation of the HttpMessageHandler. This might be useful if you want to perform a uniform task for every request or response that comes through, such as adding a security key to the header or examining incoming responses for a correct format.

You must use caution when adding custom code to your HttpMessageHandler on the client-side, however. The idea behind a Web API service is that the functionality can be called by a wide variety of clients. Putting too much logic about the transaction on the client-side may require replicating that code on every client that uses the service. This is something that you should generally avoid, or at the very least, clients should have other ways to provide that information to the service other than requiring a custom HttpMessageHandler on the client-side.


ldn-pledgerwoodThis post is an excerpt from the online courseware for our
ASP.NET Web API HTTP Pipeline course written by expert Philip Ledgerwood.

Philip Ledgerwood has been a software developer for fifteen years. He currently works primarily in .NET technologies producing custom software for organizations of all sizes. He has also done extensive training for those same organizations in both technical and business process topics.

ASP.NET Web APIs: Alternative Routing Conventions

aspnet tutorial1

 

Like ASP.NET MVC framework routing, you can change the default route mappings to a different pattern. This is rarely necessary, however. What is more common is the need to change the default way the Web API identifies a controller action, and Web API routing gives you several options to do this.

HTTP Method Attributes

You can explicitly bind HTTP methods to actions in the controller. This is handy if you feel the default naming conventions force you to write action methods that aren’t very self-descriptive. For instance, having a controller method named “Put” doesn’t explicitly tell you what it’s doing. Even a name like “PutBook” doesn’t really imply that a Book is being edited. Perhaps you’d rather use a name like “EditBook” or “UpdateBook.” All you have to do is explicitly bind the PUT method to that action by using an HttpMethod attribute.

This forces the routing to use the EditBook method for a PUT request that comes in for that controller.

AcceptVerbs Attribute

The AcceptVerbs attribute is used similarly to the HTTP method attributes. It is useful when you want to specify a list of methods tied to the action and/or HTTP methods besides the usual four (GET, POST, PUT, DELETE).

Action Names in the URL

Much like the ASP.NET MVC framework, you can set up Web API routing to look for an action name in the URL and use that action to process the request. This is not generally recommended as it is a step away from a truly RESTful service. You want URLs to describe a resource, not an action to perform on the resource.

However, if your routing becomes unduly complicated or you want to keep to the same patterns your developers are used to from ASP.NET MVC, you can set up a routing table to look for action names in the URL. First change the routing table in Global.asax to the following:

Then use the HTTP method attributes on your actions:

This action would fire in response to a URL such as:


ldn-pledgerwoodThis post is an excerpt from the online courseware for our ASP.NET Web API Basics course written by expert Philip Ledgerwood.

Philip Ledgerwood has been a software developer for fifteen years. He currently works primarily in .NET technologies producing custom software for organizations of all sizes. He has also done extensive training for those same organizations in both technical and business process topics.

ASP.NET Web API’s: Default Mapping

Web API Routing

If you have used the MVC pattern in your web applications, you are already familiar with the concept of URL routing. The ASP.NET MVC framework, for instance, knows which controller action to call by looking at pieces of the URL and using those pieces to identify the controller and the controller action.

Web API routing works in a similar way, except that the action is not specified in the URL. Instead, the action is selected based on the HTTP method used in the request.

Default Mapping

Like the ASP.NET MVC framework, you can find the default routing table for the Web API in Global.asax.

Contrast this with the default routing table for ASP.NET MVC controllers:

The differences in the properties that are set and the URL mapping pattern may seem subtle, but they are important. Not only do the two mapping schemes they also capture the primary differences between a RESTful API and something that maps to method names in a URL.

The first difference is the MapHttpRoute method. This method is used to map API routes as opposed to the MapRoute method, which is used for ASP.NET MVC routing tables.

The second difference is that “api” is a hard-coded value in the Web API map for URLs. This prevents mapping conflicts with the ASP.NET MVC framework. It’s quite possible for both your MVC controllers and your Web API controllers to have the same names, so having “api” as part of all Web API URLs makes sure your routing table uses the right controller for a request.

The third difference is that the routeTemplate does not have an action parameter like the ASP.NET MVC framework routes do. In ASP.NET MVC, the URL specifies the action that should be called. In the Web API, the API decides which action should be called based on the HTTP method handled bythe controller.

In order to map a request to a controller action, Web API routing goes through the following steps:

  1. Checks for an “api” in the beginning. If there isn’t one, it is handled by MVC routing, instead.
  2. Adds the word “Controller” to the value found in the {controller} parameter of the URL and uses this to find the appropriate Web API controller
  3. Looks for an action with a name that begins with the HTTP method used in the request. For instance, if a GET method is used, Web API will look for an action name that starts with the word “Get,” a POST method willtrigger an action that starts with the word “Post,” and so on.
  4. Maps any additional parameters to action parameters.

Table 1 shows how the HTTP method and the URL pattern will map to actions by default. Once again, remember that the action name only has to begin with the HTTP method name; everything else is irrelevant and can be whatever you want.

HTTP Method URL Matching Action
GET api/books GetAllBooks()
GET api/books/2 GetBook(int id)
POST api/books PostNewBook()
PUT api/books/2 DeleteBook(int id)
DELETE api/books/2 DeleteBook(int id)

Table 1. Example HTTP requests mapping to controller actions.

This post is an excerpt from the online courseware for our ASP.NET Web API Basics course written by expert Philip Ledgerwood.

ldn-pledgerwoodPhilip Ledgerwood has been a software developer for fifteen years. He currently works primarily in .NET technologies producing custom software for organizations of all sizes. He has also done extensive training for those same organizations in both technical and business process topics.