Configure ASP.NET Web API 2

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

Configuration settings

The HttpConfiguration class is defined in the Web API configuration settings .

member description
DependencyResolver Make the controller's dependency injection. See Using the Web API dependency resolver .
Filter Action filter.
Formatter Media type formatter .
IncludeErrorDetailPolicy Specify whether the server should include error details in the HTTP response message, such as exception messages and stack traces. See IncludeErrorDetailPolicy .
Initializer The final initialization function HttpConfiguration executed .
MessageHandlers HTTP message handler .
ParameterBindingRules The set of bound parameters on the controller operation of the rule.
Attributes A generic property bag.
routing A collection of routes. See Routing in ASP.NET Web API .
service Service collection. See Services .

System essential

Visual Studio 2017 Community、 Professional 或 Enterprise edition。

Configure Web API hosted with ASP.NET

In ASP.NET applications, configure the application_start method in Web API GlobalConfiguration.Configure by calling . The configuration method uses a delegate with a parameter of type HttpConfiguration . Perform all commissioned internal configuration.

The following is an example of using anonymous delegation:

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 will automatically set the configuration code, if you select "Web API" in the new ASP.NET project dialog box.
Insert picture description here
Project will create a template named in the application WebApiConfig.csfile \_to start folder. This definition should be placed into the code file Web APIconfiguration code delegate.
Insert picture description here

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 will also add calls to the application_launch from the delegated code .

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

Configuration Web APIand OWINself-hosted

If you bring OWIN self-hosted, please create a new HttpConfiguration instance. Perform any configuration on this instance and then pass it to the Owin.UseWebApi extension method of the instance .

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); 
    } 
}

This tutorial 使用 OWIN 自托管 ASP.NET Web API 2shows the steps to complete.

Global Web API service

HttpConfiguration.Services collection contains a set Web APIused to perform various tasks, such as controller selection and global content negotiation services.

[!NOTE]
Services collection is not a general mechanism for service discovery or dependency injection. It is only stored to service types known to the Web API framework.
The Services collection is initialized with a set of default services, and you can provide your own custom implementation. Some services support multiple instances, while others can have only one instance. (However, you can also provide services at the controller level; please refer to each controller configuration .

Single instance service

service description
IActionValueBinder Get the parameter binding.
IApiExplorer Get the description of the APIs exposed by the application. See the help page for creating a Web API .
IAssembliesResolver Get a list of the application's assemblies. See routing and operation selection .
IBodyModelValidator Verify the model read from the media type formatter of the request body.
IContentNegotiator Perform content negotiation.
IDocumentationProvider Provides documentation about Api. The default value is null . See the help page for creating a Web API .
IHostBufferPolicySelector Indicates whether the host should buffer the body of the HTTP message.
IHttpActionInvoker Invoke the controller operation. See routing and operation selection .
IHttpActionSelector Controller operation is selected. See routing and operation selection .
IHttpControllerActivator Activate a controller. See routing and operation selection .
IHttpControllerSelector Select the controller. See routing and operation selection .
IHttpControllerTypeResolver Provides a series of Web API controller types in applications. See routing and operation selection .
ITraceManager Initialize the tracking framework. See Tracking in ASP.NET Web API .
ITraceWriter A trace writer is provided. The default value is "no op" trace writer. See Tracking in ASP.NET Web API .
ImodelValidatorCache Provide a cache for the model validator.

Multi-instance service

service description
IFilterProvider Returns a list of filters operated by the controller.
ModelBinderProvider Returns the model binder of the given type.
ModelMetadataProvider Provide model metadata.
ModelValidatorProvider Provide verification procedures for the model.
ValueProviderFactory Create a value provider. For more information, see Mike Stall's blog post How to create a custom value provider in WebAPI

To add to a custom implementation of a multi-instance service, call out or insert into the Services collection:

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

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

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

Per controller configuration

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

  • Media type formatter
  • Parameter binding rules
  • Services

To perform this operation, you can define a custom property implemented by the IControllerConfiguration interface. Then apply this feature to the controller.

The following example replaces the default media type formatter 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...
    }
}

IControllerConfiguration.Initialize The method takes two parameters:

  • HttpControllerSettings object
  • HttpControllerDescriptor object

HttpControllerDescriptor contains the controller, it can check the description used to provide information (for example, to distinguish two controllers).

Use HttpControllerSettings to configure the controller object. This object is included at the base of each controller, and you can override a subset of configuration parameters. Do not change any settings. The default is the global HttpConfiguration object.

Guess you like

Origin blog.csdn.net/WuLex/article/details/113449069