設定 ASP.NET Web API 2Configuring ASP.NET Web API 2

藉由Mike Wassonby Mike Wasson

本主題描述如何設定 ASP.NET Web API。This topic describes how to configure ASP.NET Web API.

組態設定Configuration Settings

Web API 組態設定會定義在HttpConfiguration類別。Web API configuration settings are defined in the HttpConfiguration class.

成員Member 描述Description
DependencyResolverDependencyResolver 可讓控制站的相依性插入。Enables dependency injection for controllers. 請參閱使用 Web API 的相依性解析程式See Using the Web API Dependency Resolver.
篩選Filters 動作篩選條件。Action filters.
格式器Formatters 媒體類型格式器Media-type formatters.
IncludeErrorDetailPolicyIncludeErrorDetailPolicy 指定伺服器是否應該在 HTTP 回應訊息中包含錯誤詳細資料,例如例外狀況訊息和堆疊追蹤。Specifies whether the server should include error details, such as exception messages and stack traces, in HTTP response messages. 請參閱IncludeErrorDetailPolicySee IncludeErrorDetailPolicy.
初始設定式Initializer 執行最後的初始化函式HttpConfigurationA function that performs final initialization of the HttpConfiguration.
MessageHandlersMessageHandlers HTTP 訊息處理常式HTTP message handlers.
ParameterBindingRulesParameterBindingRules 用於控制器動作上的繫結參數的規則集合。A collection of rules for binding parameters on controller actions.
屬性Properties 泛型屬性包。A generic property bag.
路由Routes 路由的集合。The collection of routes. 請參閱ASP.NET Web API 中的路由See Routing in ASP.NET Web API.
服務Services 服務集合。The collection of services. 請參閱ServicesSee Services.

必要條件Prerequisites

Visual Studio 2017 Community、 Professional 或 Enterprise edition。Visual Studio 2017 Community, Professional, or Enterprise edition.

設定與 ASP.NET 裝載的 Web APIConfiguring Web API with ASP.NET Hosting

在 ASP.NET 應用程式,請藉由呼叫中設定 Web API GlobalConfiguration.Configure應用程式_啟動方法。In an ASP.NET application, configure Web API by calling GlobalConfiguration.Configure in the Application_Start method. 設定方法會接受具有單一參數型別的委派HttpConfigurationThe 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 }
                );
            });
        }
    }
}

在 Visual Studio 2017 中,「 ASP.NET Web 應用程式 」 專案範本會自動設定的組態程式碼中,如果您選取 Web API 」 中新的 ASP.NET 專案對話方塊。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.

專案範本會建立名為 「 應用程式的 WebApiConfig.cs 檔案_開始資料夾。The project template creates a file named WebApiConfig.cs inside the App_Start folder. 這個程式碼檔會定義應放置您的 Web API 組態程式碼的委派。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);
    }
}

設定 Web API 與 OWIN 自我裝載Configuring Web API with OWIN Self-Hosting

如果您是使用 OWIN 自我裝載,建立新HttpConfiguration執行個體。If you are self-hosting with OWIN, create a new HttpConfiguration instance. 在此情況下,執行任何設定,然後將傳遞至執行個體Owin.UseWebApi擴充方法。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); 
    } 
}

本教學課程使用 OWIN 自我裝載 ASP.NET Web API 2顯示完成的步驟。The tutorial Use OWIN to Self-Host ASP.NET Web API 2 shows the complete steps.

全域的 Web API 服務Global Web API Services

HttpConfiguration.Services集合包含一組 Web API 用來執行各種工作,例如控制器選取項目和內容交涉的全域服務。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

Services集合不是服務探索或相依性插入的一般用途機制。The Services collection is not a general-purpose mechanism for service discovery or dependency injection. 它只會儲存 Web API 架構已知的服務類型。It only stores service types that are known to the Web API framework.

Services集合已初始化與一組預設的服務,而且您可以提供您自己的自訂實作。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
IActionValueBinderIActionValueBinder 取得參數繫結。Gets a binding for a parameter.
IApiExplorerIApiExplorer 取得描述元的應用程式所公開的 Api。Gets descriptions of the APIs exposed by the application. 請參閱建立 Web API 說明頁面See Creating a Help Page for a Web API.
IAssembliesResolverIAssembliesResolver 取得應用程式的組件清單。Gets a list of the assemblies for the application. 請參閱路由和動作選取See Routing and Action Selection.
IBodyModelValidatorIBodyModelValidator 驗證的模型,會從要求主體讀取媒體類型格式器。Validates a model that is read from the request body by a media-type formatter.
IContentNegotiatorIContentNegotiator 執行內容交涉。Performs content negotiation.
IDocumentationProviderIDocumentationProvider 提供 Api 的文件。Provides documentation for APIs. 預設值是nullThe default is null. 請參閱建立 Web API 說明頁面See Creating a Help Page for a Web API.
IHostBufferPolicySelectorIHostBufferPolicySelector 表示主機是否應緩衝 HTTP 訊息實體內文。Indicates whether the host should buffer HTTP message entity bodies.
IHttpActionInvokerIHttpActionInvoker 叫用控制器動作。Invokes a controller action. 請參閱路由和動作選取See Routing and Action Selection.
IHttpActionSelectorIHttpActionSelector 選取控制器動作。Selects a controller action. 請參閱路由和動作選取See Routing and Action Selection.
IHttpControllerActivatorIHttpControllerActivator 啟動控制站。Activates a controller. 請參閱路由和動作選取See Routing and Action Selection.
IHttpControllerSelectorIHttpControllerSelector 選取控制器。Selects a controller. 請參閱路由和動作選取See Routing and Action Selection.
IHttpControllerTypeResolverIHttpControllerTypeResolver 提供一份應用程式中的 Web API 控制器類型。Provides a list of the Web API controller types in the application. 請參閱路由和動作選取See Routing and Action Selection.
ITraceManagerITraceManager 初始化追蹤架構。Initializes the tracing framework. 請參閱ASP.NET Web API 中追蹤See Tracing in ASP.NET Web API.
ITraceWriterITraceWriter 提供的追蹤寫入器。Provides a trace writer. 預設為 「 無操作 」 追蹤寫入器。The default is a "no-op" trace writer. 請參閱ASP.NET Web API 中追蹤See Tracing in ASP.NET Web API.
IModelValidatorCacheIModelValidatorCache 提供模型驗證程式的快取。Provides a cache of model validators.

多個執行個體的服務Multiple-Instance Services

服務Service 描述Description
IFilterProviderIFilterProvider 傳回控制器動作篩選條件的清單。Returns a list of filters for a controller action.
ModelBinderProviderModelBinderProvider 傳回指定型別的模型繫結。Returns a model binder for a given type.
ModelMetadataProviderModelMetadataProvider 提供模型中繼資料。Provides metadata for a model.
ModelValidatorProviderModelValidatorProvider 提供模型驗證程式。Provides a validator for a model.
ValueProviderFactoryValueProviderFactory 建立值提供者。Creates a value provider. 如需詳細資訊,請參閱 Mike Stall 的部落格文章如何在 WebAPI 中建立的自訂值提供者For more information, see Mike Stall's blog post How to create a custom value provider in WebAPI

若要加入多個執行個體服務的自訂實作,請呼叫新增或是插入Services集合: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

若要這樣做,請定義自訂屬性,以實作IControllerConfiguration介面。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...
    }
}

IControllerConfiguration.Initialize方法採用兩個參數:The IControllerConfiguration.Initialize method takes two parameters:

  • HttpControllerSettings物件An HttpControllerSettings object
  • HttpControllerDescriptor物件An HttpControllerDescriptor object

HttpControllerDescriptor包含控制器,您可以檢查僅供參考之用 (例如,若要區別兩個控制站) 的描述。The HttpControllerDescriptor contains a description of the controller, which you can examine for informational purposes (say, to distinguish between two controllers).

使用HttpControllerSettings設定控制站的物件。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. 您不會變更任何設定預設為全域HttpConfiguration物件。Any settings that you don't change default to the global HttpConfiguration object.