Configuring Web API

You may have been wondering about the Configuration property on the controller. In traditional ASP.NET applications, application configuration is done in Global.asax, and the application uses global state (including statics and thread local variables) to give access to the request and application configuration.

Web API was designed not to have any such static global values, and instead put its configuration into the HttpConfiguration class. This has two impacts on application design: First, you can run multiple Web API servers in the same application (since each server has its own non-global configuration); second, you can run both unit tests and end to end tests more easily in Web API, since you contain that configuration into a single non-global object, as statics make parallelized testing much more challenging. The configuration class includes access to the following items:

  • Routes
  • Filters to run for all requests
  • Parameter binding rules
  • The default formatters used for reading and writing body content
  • The default services used by Web API
  • A user-provided dependency resolver for DI on services and controllers
  • HTTP message handlers
  • A flag for whether to include error details like stack traces
  • A Properties bag which can hold user-defined values

How you create or get access to this configuration depends on how you are hosting your application: inside ASP.NET or inside WCF self-host.

Configuration in Web-Hosted Web API

The default MVC project templates are all web-hosted projects, since MVC only supports web-hosting. Inside the App_Startup folder you'll find the startup configuration files for your MVC application. The Web API configuration code is in WebApiConfig.cs (or .vb), and looks something like this:

public static class WebApiConfig {
    public static void Register(HttpConfiguration config) {

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

Developers will make modifications to this file to reflect any configuration changes they wish to make for their application. The default contains a single route as an example to get you started.

If you look inside Global.asax, you'll see that this configuration function is called by passing in the GlobalConfiguration.Configuration object. Web-hosted Web API only supports a single server and single configuration file, and the developer is not responsible for creating these, only for configuring them as appropriate. The GlobalConfiguration class is found in the assembly System.Web.Http.WebHost.dll, as is the rest of the infrastructure needed to support web-hosted Web APIs.

Configuration in Self-Hosted Web API

The other host that ships with Web API is a WCF-based self-host. The code this host is contained in is the assembly System.Web.Http.SelfHost.dll.

There are no built-in project templates for self-hosting because there is no limitation to the project type that you may want to use when self-hosting. You may be hosting inside of a console application, or inside of a GUI application, or even inside of a Windows Service. The simplest way to get Web API running in your application is to use NuGet to install the self-host Web API package (named Microsoft.AspNet.WebApi.SelfHost), which will include all the System.Net.Http and System.Web.Http dependencies automatically.

When self-hosting, you are responsible for creating the configuration and starting and stopping the Web API server as appropriate. The configuration class you need to instantiate is HttpSelfHostConfiguration, which extends the base HttpConfiguration class by requiring a base URL to listen to. After setting up the configuration, you will create an instance of HttpSelfHostServer, and then tell it to start listening.

Here is an example snippet of startup code for self-host:

var config = new HttpSelfHostConfiguration("http://localhost:8080/");
config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);
var server = new HttpSelfHostServer(config);
server.OpenAsync().Wait();

You should also shut down the server when you're done:

server.CloseAsync().Wait();

If you are self-hosting in a console app, you would probably run this code in your Main function. For self-hosting in other application types, just find the appropriate place to run application startup and shutdown code and run these things there. In both cases, the .Wait() call could (and should) be replaced with an async code (using async and await) if your application development framework allows you to write an asynchronous startup and shutdown code.

Configuration in Third-Party Hosts

The hosting system for Web API is pluggable. Configuration for these hosts will be dependent on the hosting system, so please see the host documentation to determine how configuration is accomplished.

Note
The subject of writing a third-party host is beyond the scope of this book. If you are interested in writing a Web API host, please start a discussion on the ASP.NET Web API forums at http://forums.asp.net/1246.aspx.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset