Language

Configuring ASP.NET Web API 2

By Mike Wasson|

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

Configuration Settings

Web API configuration setttings are defined in the HttpConfiguration class.

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.

Configuring Web API with ASP.NET Hosting

In an ASP.NET application, configure Web API by calling GlobalConfiguration.Configure in the Application_Start method. The Configure method takes a delegate with a single parameter of type HttpConfiguration. Perform all of your configuation inside the delegate.

Here is an example using an anonymous delegate:

using System.Web.Http;
namespace WebApplication1
{
    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            GlobalConfiguration.Configure(config =>
            {
                config.MapHttpAttributeRoutes();

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

In Visual Studio 2013, the "ASP.NET Web Application" project template automatically sets up the configuration code, if you select "Web API" in the New ASP.NET Project dialog.

The project template creates a file named WebApiConfig.cs inside the App_Start folder. This code file defines the delegate where you should put your Web API configuration code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace WebApplication1
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // TODO: Add any additional configuration code.

            // Web API routes
            config.MapHttpAttributeRoutes();

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

The project template also adds the code that calls the delegate from Application_Start.

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        GlobalConfiguration.Configure(WebApiConfig.Register);
    }
}

Configuring Web API with OWIN Self-Hosting

If you are self-hosting with OWIN, create a new HttpConfiguration instance. Perform any configuration on this instance, and then pass the instance to the Owin.UseWebApi extension method.

public class Startup 
{ 
    public void Configuration(IAppBuilder appBuilder) 
    { 
        HttpConfiguration config = new HttpConfiguration(); 

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

        appBuilder.UseWebApi(config); 
    } 
} 

The tutorial Use OWIN to Self-Host ASP.NET Web API 2 shows the complete steps.

Global 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. It only stores service types that are known to the Web API 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 add a custom implementation to a multi-instance service, call Add or Insert on the Services collection:

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

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

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

Per-Controller Configuration

You can override the following settings on a per-controller basis:

  • Media-type formatters
  • Parameter binding rules
  • Services

To do so, define a custom attribute that implements the IControllerConfiguration interface. Then apply the attribute to the controller.

The following example replaces the default media-type formatters with a custom formatter.

using System;
using System.Web.Http;
using System.Web.Http.Controllers;

namespace WebApplication1.Controllers
{

    public class UseMyFormatterAttribute : Attribute, IControllerConfiguration
    {
        public void Initialize(HttpControllerSettings settings,
            HttpControllerDescriptor descriptor)
        {
            // Clear the formatters list.
            settings.Formatters.Clear();

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

    [UseMyFormatter]
    public class ValuesController : ApiController
    {
        // Controller methods not shown...
    }
}

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. Any settings that you don't change default to the global HttpConfiguration object.

Author Information

Mike Wasson

Mike Wasson – Mike Wasson is a programmer-writer at Microsoft.