Configuring ASP.NET Web API
This topic describes how to configure ASP.NET Web API.
- Global Configuration Settings (ASP.NET Hosting)
- Global Configuration Settings (Self-Hosting)
- Services
- Per-Controller Configuration
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.
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. |
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.
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. |
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 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.
Comments (0) RSS Feed