Tag Archives: web API

ASP.NET Web API: Self-Hosting

aspnet tutorial1

Building a service-oriented architecture with the ASP.NET Web API does not restrict you to IIS deployment. This may come as a surprise to those who have worked with Microsoft technologies for a long time. Many Microsoft technologies for the web are designed to be deployed on IIS and become erratic or completely non-functional if deployed in some other way. The Web API, however, does not need to be deployed in IIS, or even deployed to a web server. Microsoft has put the tools in the framework necessary to host Web API services out of any application you write.

Hosting Web API services in your own process is called self-hosting. You might think that self-hosting is an intensely involved process that has to manage sockets, multiple threads, etc. However, the framework has two objects that wrap up most of this complexity for you: HttpSelfHostConfiguration and HttpSelfHostServer.

The HttpSelfHostConfiguration object provides information to the framework on how you want the host to work. At the very least, this includes specifying the root URL that the host will use for HTTP requests and the routing rule(s) used. If all you intend to host are Web API services, then you can simply copy and paste the routing rule from the Global.asax of a Web API application.

WARNING! Make sure the application that you’re writing has adequate permissions to commandeer ports. Also, make sure that the machine running your application can receive HTTP requests from other machines on your network or outside your network depending on your needs. If your application can process requests made on that machine but not from any others, that could be a sign that the machine can’t be accessed from the outside. Finally, make sure your application’s build is targeted for the .NET 4 Framework and not the .NET 4 Framework Client Profile.

The HttpSelfHostServer takes in the second object: an HttpSelfHostConfiguration object. In your code, simply use the OpenAsync and Wait methods of this object for it to start listening for HTTP requests. Any HTTP requests that hit the URL defined in the HttpSelfHostConfiguration will run through the routing rules also defined in that configuration and get routed accordingly. From that point, everything works just like a normal Web API application. It’s almost as if you’ve written your own miniature web server as part of some other program. This code is quite simple considering the complexity of what you’re actually doing. Self-hosting can be useful in situations where IIS is not an option, where you have a very tightly-focused application that needs to handle everything internally, or you have various applications that need to communicate with each other across HTTP.

TIP: In order to use these objects, it is important that you have the MVC4 and selfhosting DLLs available to your code. The easiest way to get them is from the NuGet package Microsoft.AspNet.WebApi.SelfHost.


ldn-pledgerwoodThis post is an excerpt from the online courseware for our
ASP.NET Web API Hosting and Dependency Resolution 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.

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’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.