Configuring ASP.NET Web API 2

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

Configuration Settings

Web API configuration settings are defined in the HttpConfiguration class.

Member Description
DependencyResolver Enables dependency injection for controllers. See Using the Web API Dependency Resolver.
Filters Action filters.
Formatters Media-type formatters.
IncludeErrorDetailPolicy Specifies whether the server should include error details, such as exception messages and stack traces, in HTTP response messages. See IncludeErrorDetailPolicy.
Initializer A function that performs final initialization of the HttpConfiguration.
MessageHandlers HTTP message handlers.
ParameterBindingRules A collection of rules for binding parameters on controller actions.
Properties A generic property bag.
Routes The collection of routes. See Routing in ASP.NET Web API.
Services The collection of services. See Services.

Prerequisites

Visual Studio 2017 Community, Professional, or Enterprise edition.

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 configuration 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 2017, 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.

Screenshot of New A S P dot NET Project dialog, with Web A P I checkbox selected to automatically set up configuration code.

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.

Screenshot of Solution Explorer dialog, with Web A P I Config dot c s outlined in red, inside App Start folder.

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.

Note

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

Service Description
IActionValueBinder Gets a binding for a parameter.
IApiExplorer Gets descriptions of the APIs exposed by the application. See Creating a Help Page for a Web API.
IAssembliesResolver Gets a list of the assemblies for the application. See Routing and Action Selection.
IBodyModelValidator Validates a model that is read from the request body by a media-type formatter.
IContentNegotiator Performs content negotiation.
IDocumentationProvider Provides documentation for APIs. The default is null. See Creating a Help Page for a Web API.
IHostBufferPolicySelector Indicates whether the host should buffer HTTP message entity bodies.
IHttpActionInvoker Invokes a controller action. See Routing and Action Selection.
IHttpActionSelector Selects a controller action. See Routing and Action Selection.
IHttpControllerActivator Activates a controller. See Routing and Action Selection.
IHttpControllerSelector Selects a controller. See Routing and Action Selection.
IHttpControllerTypeResolver Provides a list of the Web API controller types in the application. See Routing and Action Selection.
ITraceManager Initializes the tracing framework. See Tracing in ASP.NET Web API.
ITraceWriter Provides a trace writer. The default is a "no-op" trace writer. See Tracing in ASP.NET Web API.
IModelValidatorCache Provides a cache of model validators.

Multiple-Instance Services

Service Description
IFilterProvider Returns a list of filters for a controller action.
ModelBinderProvider Returns a model binder for a given type.
ModelMetadataProvider Provides metadata for a model.
ModelValidatorProvider Provides a validator for a model.
ValueProviderFactory Creates 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.