使用 Web API 慣例Use web API conventions

作者:Pranav KrishnamoorthyScott AddieBy Pranav Krishnamoorthy and Scott Addie

ASP.NET Core 2.2 和更新版本包含擷取常見 API 文件的方式,並將其套用至多個動作、控制器,或組件內的所有控制器。ASP.NET Core 2.2 and later includes a way to extract common API documentation and apply it to multiple actions, controllers, or all controllers within an assembly. Web API 慣例為使用 [ProducesResponseType] 裝飾個別動作的替代品。Web API conventions are a substitute for decorating individual actions with [ProducesResponseType].

慣例可讓您:A convention allows you to:

  • 定義從特定動作類型傳回的最常見傳回型別和狀態碼。Define the most common return types and status codes returned from a specific type of action.
  • 識別偏離已定義標準的動作。Identify actions that deviate from the defined standard.

ASP.NET Core MVC 2.2 和更新版本在 Microsoft.AspNetCore.Mvc.DefaultApiConventions 中包含一組預設慣例。ASP.NET Core MVC 2.2 and later includes a set of default conventions in Microsoft.AspNetCore.Mvc.DefaultApiConventions. 這些慣例是以 ASP.NET Core API 專案範本中所提供的控制器 (ValuesController.cs) 為基礎。The conventions are based on the controller (ValuesController.cs) provided in the ASP.NET Core API project template. 若動作遵循範本中的模式,就應該可以成功使用預設慣例。If your actions follow the patterns in the template, you should be successful using the default conventions. 如果預設慣例不符合您的需求,請參閱建立 Web API 慣例If the default conventions don't meet your needs, see Create web API conventions.

在執行階段,Microsoft.AspNetCore.Mvc.ApiExplorer 了解慣例。At runtime, Microsoft.AspNetCore.Mvc.ApiExplorer understands conventions. ApiExplorer 是 MVC 與 OpenAPI (也稱為 Swagger) 文件產生器通訊的抽象層。ApiExplorer is MVC's abstraction to communicate with OpenAPI (also known as Swagger) document generators. 來自套用慣例的屬性會與動作建立關聯,且包含在動作的 OpenAPI 文件中。Attributes from the applied convention are associated with an action and are included in the action's OpenAPI documentation. API 分析器也了解慣例。API analyzers also understand conventions. 若您的動作為非傳統的 (例如,其傳回未由套用慣例所記載的狀態碼),就會出現警告,建議您記載狀態碼。If your action is unconventional (for example, it returns a status code that isn't documented by the applied convention), a warning encourages you to document the status code.

檢視或下載範例程式碼 (英文) (如何下載)View or download sample code (how to download)

套用 Web API 慣例Apply web API conventions

慣例不會進行撰寫;各個動作可能僅會與一個慣例建立關聯。Conventions don't compose; each action may be associated with exactly one convention. 相較於較不特定的慣例,更特定的慣例擁有較高的優先順序。More specific conventions take precedence over less specific conventions. 當兩個以上相同屬性的慣例套用至動作時,慣例就具有不確定性。The selection is non-deterministic when two or more conventions of the same priority apply to an action. 下列選項的作用為將慣例套用至動作,其順序為從最特定到最不特定:The following options exist to apply a convention to an action, from the most specific to the least specific:

  1. Microsoft.AspNetCore.Mvc.ApiConventionMethodAttribute — 會套用至個別動作,並會指定慣例型別及其套用的慣例方法。Microsoft.AspNetCore.Mvc.ApiConventionMethodAttribute — Applies to individual actions and specifies the convention type and the convention method that applies.

    在下列範例中,預設慣例類型的 Microsoft.AspNetCore.Mvc.DefaultApiConventions.Put 慣例方法會套用至 Update 動作:In the following example, the default convention type's Microsoft.AspNetCore.Mvc.DefaultApiConventions.Put convention method is applied to the Update action:

    // PUT api/contactsconvention/{guid}
    [HttpPut("{id}")]
    [ApiConventionMethod(typeof(DefaultApiConventions), 
                         nameof(DefaultApiConventions.Put))]
    public IActionResult Update(string id, Contact contact)
    {
        var contactToUpdate = _contacts.Get(id);
    
        if (contactToUpdate == null)
        {
            return NotFound();
        }
    
        _contacts.Update(contact);
    
        return NoContent();
    }
    

    Microsoft.AspNetCore.Mvc.DefaultApiConventions.Put 慣例方法會將下列屬性套用至動作:The Microsoft.AspNetCore.Mvc.DefaultApiConventions.Put convention method applies the following attributes to the action:

    [ProducesDefaultResponseType]
    [ProducesResponseType(StatusCodes.Status204NoContent)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    

    如需有關 [ProducesDefaultResponseType],的詳細資訊,請參閱預設回應 (英文)。For more information on [ProducesDefaultResponseType], see Default Response.

  2. 套用到控制器的 Microsoft.AspNetCore.Mvc.ApiConventionTypeAttribute — 會將指定的慣例類型套用至控制器上的所有動作。Microsoft.AspNetCore.Mvc.ApiConventionTypeAttribute applied to a controller — Applies the specified convention type to all actions on the controller. 慣例方法由提示所裝飾,且該提示會決定要套用慣例方法的動作。A convention method is decorated with hints that determine the actions to which the convention method applies. 如需提示的詳細資訊,請參閱建立 Web API 慣例For more information on hints, see Create web API conventions).

    在下列範例中,會將一組預設的慣例套用至 ContactsConventionController 中的所有動作:In the following example, the default set of conventions is applied to all actions in ContactsConventionController:

    [ApiController]
    [ApiConventionType(typeof(DefaultApiConventions))]
    [Route("api/[controller]")]
    public class ContactsConventionController : ControllerBase
    {
    
  3. 套用至組件的 Microsoft.AspNetCore.Mvc.ApiConventionTypeAttribute — 會將指定的慣例類型套用至目前組件中的所有控制器。Microsoft.AspNetCore.Mvc.ApiConventionTypeAttribute applied to an assembly — Applies the specified convention type to all controllers in the current assembly. 建議您套用 Startup.cs 檔案中的組件層級屬性。As a recommendation, apply assembly-level attributes in the Startup.cs file.

    在下列範例中,會將一組預設的慣例套用至組件中的所有控制器:In the following example, the default set of conventions is applied to all controllers in the assembly:

    [assembly: ApiConventionType(typeof(DefaultApiConventions))]
    namespace ApiConventions
    {
        public class Startup
        {
    

建立 Web API 慣例Create web API conventions

如果預設 API 慣例不符合您的需求,請建立您自己的慣例。If the default API conventions don't meet your needs, create your own conventions. 慣例為:A convention is:

回應類型Response types

使用 [ProducesResponseType][ProducesDefaultResponseType] 屬性標註這些方法。These methods are annotated with [ProducesResponseType] or [ProducesDefaultResponseType] attributes. 例如:For example:

public static class MyAppConventions
{
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public static void Find(int id)
    {
    }
}

如果沒有更特定的中繼資料屬性,將此慣例套用至組件可確保:If more specific metadata attributes are absent, applying this convention to an assembly enforces that:

  • 將慣例方法套用至任何名為 Find 的動作。The convention method applies to any action named Find.
  • Find 動作中有名為 id 的參數。A parameter named id is present on the Find action.

命名需求Naming requirements

您可以將 [ApiConventionNameMatch][ApiConventionTypeMatch] 屬性套用至會決定其套用動作的慣例方法。The [ApiConventionNameMatch] and [ApiConventionTypeMatch] attributes can be applied to the convention method that determines the actions to which they apply. 例如:For example:

[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ApiConventionNameMatch(ApiConventionNameMatchBehavior.Prefix)]
public static void Find(
    [ApiConventionNameMatch(ApiConventionNameMatchBehavior.Suffix)]
    int id)
{ }

在上述範例中:In the preceding example:

  • 套用至方法的 Microsoft.AspNetCore.Mvc.ApiExplorer.ApiConventionNameMatchBehavior.Prefix 選項表示慣例會比對任何前置詞為 "Find" 的動作。The Microsoft.AspNetCore.Mvc.ApiExplorer.ApiConventionNameMatchBehavior.Prefix option applied to the method indicates that the convention matches any action prefixed with "Find". 相符動作範例包括 FindFindPetFindByIdExamples of matching actions include Find, FindPet, and FindById.
  • 套用至參數的 Microsoft.AspNetCore.Mvc.ApiExplorer.ApiConventionNameMatchBehavior.Suffix 表示慣例會比對只有一個以後置詞識別碼結尾之參數的方法。The Microsoft.AspNetCore.Mvc.ApiExplorer.ApiConventionNameMatchBehavior.Suffix applied to the parameter indicates that the convention matches methods with exactly one parameter ending in the suffix identifier. 範例包括 idpetId 等參數。Examples include parameters such as id or petId. 同樣地,ApiConventionTypeMatch 可套用至類型來限制參數類型。ApiConventionTypeMatch can be similarly applied to types to constrain the parameter type. params[] 引數表示其餘參數不需要明確相符。A params[] argument indicates remaining parameters that don't need to be explicitly matched.

其他資源Additional resources