Language

Configuring ASP.NET Web API

By |

This topic describes how to configure ASP.NET Web API.

Global Configuration Settings (ASP.NET Hosting)

If you are hosting in ASP.NET, the global configuration settings for Web API are stored in the GlobalConfiguration object, which is contains a singleton HttpConfiguration instance. The HttpConfiguration object contains the following members.

MemberDescription
DependencyResolverEnables dependency injection for controllers. See Using the Web API Dependency Resolver .
FiltersAction filters.
FormattersMedia-type formatters.
IncludeErrorDetailPolicySpecifies whether the server should include error details, such as exception messages and stack traces, in HTTP response messages. See IncludeErrorDetailPolicy.
InitializerA function that performs final initialization of the HttpConfiguration.
MessageHandlersHTTP message handlers.
ParameterBindingRulesA collection of rules for binding parameters on controller actions.
PropertiesA generic property bag.
RoutesThe collection of routes; see Routing in ASP.NET Web API.
ServicesThe collection of services. See Services.

Make any configuration changes inside the Application_Start method. The Visual Studio "ASP.NET MVC 4 Web Application" project template includes a class named WebApiConfig that is intended for Web API configuration.

If you create a new project using this template and open the Global.asax file, you will see that the Application_Start method looks like this:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    WebApiConfig.Register(GlobalConfiguration.Configuration);
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}

The call to WebApiConfig.Register configures Web API. The definition for the WebApiConfig class is located in the App_Start directory.

The WebApiConfig.Register method adds the default Web API route, and is a good place to add any other global configuration code for Web API.

You don't need to use the WebApiConfig class; it's simply a convenient way to organize your code.

Global Configuration Settings (Self-Hosting)

If you self-host Web API, the configuration settings are stored in the HttpSelfHostConfiguration class, which derives from HttpConfiguration. For example:

var config = new HttpSelfHostConfiguration("http://localhost:8080");

// Add a route
config.Routes.MapHttpRoute(
    "API Default", 
    "api/{controller}/{id}", 
    new { id = RouteParameter.Optional });

// Add a media-type formatter
config.Formatters.Add(new MyFormatter()); 

For more information about self-hosting, see Self-Host a Web API.

Services

The HttpConfiguration.Services collection contains a set of global services that Web API uses to perform various tasks, such as controller selection and content negotiation.

The Services collection is not a general-purpose mechanism for service discovery or dependency injection. The Services collection only stores service types that are known to the framework.

The Services collection is initialized with a default set of services, and you can provide your own custom implementations. Some services support multiple instances, while others can have only one instance. (However, you can also provide services at the controller level; see Per-Controller Configuration.

Single-Instance Services
ServiceDescription
IActionValueBinderGets a binding for a parameter.
IApiExplorerGets descriptions of the APIs exposed by the application. See Creating a Help Page for a Web API.
IAssembliesResolverGets a list of the assemblies for the application. See Routing and Action Selection.
IBodyModelValidatorValidates a model that is read from the request body by a media-type formatter.
IContentNegotiatorPerforms content negotiation.
IDocumentationProviderProvides documentation for APIs. The default is null. See Creating a Help Page for a Web API.
IHostBufferPolicySelectorIndicates whether the host should buffer HTTP message entity bodies.
IHttpActionInvokerInvokes a controller action. See Routing and Action Selection.
IHttpActionSelectorSelects a controller action. See Routing and Action Selection.
IHttpControllerActivatorActivates a controller. See Routing and Action Selection.
IHttpControllerSelectorSelects a controller. See Routing and Action Selection.
IHttpControllerTypeResolverProvides a list of the Web API controller types in the application. See Routing and Action Selection.
ITraceManagerInitializes the tracing framework. See Tracing in ASP.NET Web API.
ITraceWriterProvides a trace writer. The default is a “no-op” trace writer. See Tracing in ASP.NET Web API.
IModelValidatorCacheProvides a cache of model validators.
.
Multiple-Instance Services
ServiceDescription
IFilterProviderReturns a list of filters for a controller action.
ModelBinderProviderReturns a model binder for a given type.
ModelMetadataProviderProvides metadata for a model.
ModelValidatorProviderProvides a validator for a model.
ValueProviderFactoryCreates a value provider. For more information, see Mike Stall's blog post How to create a custom value provider in WebAPI

To replace a single-instance service with your own implementation, call Replace on the Services collection:

config.Services.Replace(typeof(ITraceWriter), new MyTraceWriter());

For multiple-instance services, call Add or Insert to add a new instance to the collection:

config.Services.Add(typeof(IFilterProvider), new MyFilterProvider());

Per-Controller Configuration

The HttpConfiguration object holds global settings for Web API. You can also override certain settings for a particular controller. The settings that you can override per controller are:

  • Media-type formatters
  • Parameter binding rules
  • Services

To configure a controller, create a custom attribute that implements the IControllerConfiguration interface. For example:

public class ControllerConfigAttribute : Attribute, IControllerConfiguration
{
    public void Initialize(HttpControllerSettings settings, 
        HttpControllerDescriptor descriptor)
    {
        // Remove the JSON formatter.
        var jsonFormatter = settings.Formatters.JsonFormatter;
        settings.Formatters.Remove(jsonFormatter);

        // Add a custom media-type formatter.
        settings.Formatters.Add(new MyFormatter());

        // Add a custom action selector.
        settings.Services.Replace(typeof(IHttpActionSelector), new MyActionSelector());
    }
}

Then apply the attribute to the controller:

[ControllerConfig]
public class ValuesController : ApiController
{
    // ...
}

The IControllerConfiguration.Initialize method takes two parameters:

  • An HttpControllerSettings object
  • An HttpControllerDescriptor object

The HttpControllerDescriptor contains a description of the controller, which you can examine for informational purposes (say, to distinguish between two controllers).

Use the HttpControllerSettings object to configure the controller. This object contains the subset of configuration parameters that you can override on a per-controller basis. The previous example modified the formatter collection and replaced the IHttpActionSelector service. Any settings that you don't change will default to the global HttpConfiguration object.

Mike Wasson

By Mike Wasson, Mike Wasson is a programmer-writer at Microsoft.

Table of Contents

Getting Started with ASP.NET Web API

Creating Web APIs

Web API Clients

Web API Routing and Actions

Working with HTTP

Formats and Model Binding

OData Support in ASP.NET Web API

Security

Hosting ASP.NET Web API

Testing and Debugging

Extensibility

Resources