Configuring ASP.NET Web API 2
by Mike Wasson
This topic describes how to configure ASP.NET Web API.
- Configuration Settings
- Configuring Web API with ASP.NET Hosting
- Configuring Web API with OWIN Self-Hosting
- Global Web API Services
- Per-Controller Configuration
Web API configuration setttings 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 configuation inside the delegate.
Here is an example using an anonymous delegate:
[!code-csharpMain]
1: using System.Web.Http;
2: namespace WebApplication1
3: {
4: public class WebApiApplication : System.Web.HttpApplication
5: {
6: protected void Application_Start()
7: {
8: GlobalConfiguration.Configure(config =>
9: {
10: config.MapHttpAttributeRoutes();
11:
12: config.Routes.MapHttpRoute(
13: name: "DefaultApi",
14: routeTemplate: "api/{controller}/{id}",
15: defaults: new { id = RouteParameter.Optional }
16: );
17: });
18: }
19: }
20: }
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.
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.
[!code-csharpMain]
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Web.Http;
5:
6: namespace WebApplication1
7: {
8: public static class WebApiConfig
9: {
10: public static void Register(HttpConfiguration config)
11: {
12: // TODO: Add any additional configuration code.
13:
14: // Web API routes
15: config.MapHttpAttributeRoutes();
16:
17: config.Routes.MapHttpRoute(
18: name: "DefaultApi",
19: routeTemplate: "api/{controller}/{id}",
20: defaults: new { id = RouteParameter.Optional }
21: );
22: }
23: }
24: }
The project template also adds the code that calls the delegate from Application_Start.
[!code-csharpMain]
1: public class WebApiApplication : System.Web.HttpApplication
2: {
3: protected void Application_Start()
4: {
5: GlobalConfiguration.Configure(WebApiConfig.Register);
6: }
7: }
## 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.
[!code-csharpMain]
1: public class Startup
2: {
3: public void Configuration(IAppBuilder appBuilder)
4: {
5: HttpConfiguration config = new HttpConfiguration();
6:
7: config.Routes.MapHttpRoute(
8: name: "DefaultApi",
9: routeTemplate: "api/{controller}/{id}",
10: defaults: new { id = RouteParameter.Optional }
11: );
12:
13: appBuilder.UseWebApi(config);
14: }
15: }
The tutorial Use OWIN to Self-Host ASP.NET Web API 2 shows the complete steps.
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:
[!code-csharpMain]
1: config.Services.Add(typeof(IFilterProvider), new MyFilterProvider());
To replace a single-instance service with a custom implementation, call Replace on the Services collection:
[!code-csharpMain]
1: 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.
[!code-csharpMain]
1: using System;
2: using System.Web.Http;
3: using System.Web.Http.Controllers;
4:
5: namespace WebApplication1.Controllers
6: {
7:
8: public class UseMyFormatterAttribute : Attribute, IControllerConfiguration
9: {
10: public void Initialize(HttpControllerSettings settings,
11: HttpControllerDescriptor descriptor)
12: {
13: // Clear the formatters list.
14: settings.Formatters.Clear();
15:
16: // Add a custom media-type formatter.
17: settings.Formatters.Add(new MyFormatter());
18: }
19: }
20:
21: [UseMyFormatter]
22: public class ValuesController : ApiController
23: {
24: // Controller methods not shown...
25: }
26: }
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.
|