使用 ASP.NET Core 建立 Web APICreate web APIs with ASP.NET Core

作者:Scott AddieTom DykstraBy Scott Addie and Tom Dykstra

ASP.NET Core 支援使用 C# 建立 RESTful 服務,也稱為 Web API。ASP.NET Core supports creating RESTful services, also known as web APIs, using C#. 若要處理要求,Web API 會使用控制器。To handle requests, a web API uses controllers. Web API 中的「控制器」都衍生自類別 ControllerBaseControllers in a web API are classes that derive from ControllerBase. 本文說明如何使用控制器來處理 web API 要求。This article shows how to use controllers for handling web API requests.

查看或下載範例程式碼View or download sample code. (如何下載)。(How to download).

ControllerBase 類別ControllerBase class

Web API 是由一或多個衍生自的控制器類別所組成 ControllerBaseA web API consists of one or more controller classes that derive from ControllerBase. Web API 專案範本提供入門控制器:The web API project template provides a starter controller:

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase

請不要從 Controller 類別衍生以建立 Web API 控制器。Don't create a web API controller by deriving from the Controller class. Controller 衍生自 ControllerBase 並會新增檢視支援,以供處理網頁,而不是 Web API 要求。Controller derives from ControllerBase and adds support for views, so it's for handling web pages, not web API requests. 這項規則有一個例外狀況:如果您打算針對 views 和 web Api 使用相同的控制器,請從衍生 ControllerThere's an exception to this rule: if you plan to use the same controller for both views and web APIs, derive it from Controller.

ControllerBase 類別提供許多處理 HTTP 要求的實用屬性和方法。The ControllerBase class provides many properties and methods that are useful for handling HTTP requests. 例如,ControllerBase.CreatedAtAction 會傳回 201 狀態碼:For example, ControllerBase.CreatedAtAction returns a 201 status code:

[HttpPost]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public ActionResult<Pet> Create(Pet pet)
{
    pet.Id = _petsInMemoryStore.Any() ? 
             _petsInMemoryStore.Max(p => p.Id) + 1 : 1;
    _petsInMemoryStore.Add(pet);

    return CreatedAtAction(nameof(GetById), new { id = pet.Id }, pet);
}

以下是 ControllerBase 提供的一些其他方法範例。Here are some more examples of methods that ControllerBase provides.

方法Method 注意Notes
BadRequest 傳回 400 狀態碼。Returns 400 status code.
NotFound 傳回 404 狀態碼。Returns 404 status code.
PhysicalFile 傳回檔案。Returns a file.
TryUpdateModelAsync 叫用模型繫結Invokes model binding.
TryValidateModel 叫用模型驗證Invokes model validation.

如需所有可用方法和屬性的清單,請參閱 ControllerBaseFor a list of all available methods and properties, see ControllerBase.

屬性Attributes

Microsoft.AspNetCore.Mvc 命名空間提供的屬性,可用來設定 Web API 控制器和動作方法的行為。The Microsoft.AspNetCore.Mvc namespace provides attributes that can be used to configure the behavior of web API controllers and action methods. 下列範例會使用屬性來指定支援的 HTTP 動作動詞以及任何可傳回的已知 HTTP 狀態碼:The following example uses attributes to specify the supported HTTP action verb and any known HTTP status codes that could be returned:

[HttpPost]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public ActionResult<Pet> Create(Pet pet)
{
    pet.Id = _petsInMemoryStore.Any() ? 
             _petsInMemoryStore.Max(p => p.Id) + 1 : 1;
    _petsInMemoryStore.Add(pet);

    return CreatedAtAction(nameof(GetById), new { id = pet.Id }, pet);
}

以下是一些其他可用的屬性範例。Here are some more examples of attributes that are available.

屬性Attribute 備註Notes
[Route] 指定控制器或動作的 URL 模式。Specifies URL pattern for a controller or action.
[Bind] 指定模型繫結要包含的前置詞和屬性。Specifies prefix and properties to include for model binding.
[HttpGet] 識別支援 HTTP GET 動作動詞的動作。Identifies an action that supports the HTTP GET action verb.
[Consumes] 指定動作所接受的資料類型。Specifies data types that an action accepts.
[Produces] 指定動作所傳回的資料類型。Specifies data types that an action returns.

如需包含可用屬性的清單,請參閱 Microsoft.AspNetCore.Mvc 命名空間。For a list that includes the available attributes, see the Microsoft.AspNetCore.Mvc namespace.

ApiController 屬性ApiController attribute

[ApiController]屬性可以套用至控制器類別,以啟用下列固定 API 特有的行為:The [ApiController] attribute can be applied to a controller class to enable the following opinionated, API-specific behaviors:

錯誤狀態碼功能的問題詳細資料 需要2.2 或更新 版本的相容性版本The Problem details for error status codes feature requires a compatibility version of 2.2 or later. 其他功能需要2.1 或更新版本的相容性版本。The other features require a compatibility version of 2.1 or later.

這些功能都需要相容性版本 2.1 或更新版本。These features require a compatibility version of 2.1 or later.

特定控制器上的屬性Attribute on specific controllers

[ApiController] 屬性可以套用至特定的控制器,如專案範本中的下列範例所示:The [ApiController] attribute can be applied to specific controllers, as in the following example from the project template:

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase

多個控制器上的屬性Attribute on multiple controllers

在多個控制站上使用同一屬性的方法之一,就是建立以 [ApiController] 屬性標註的自訂基底控制器類別。One approach to using the attribute on more than one controller is to create a custom base controller class annotated with the [ApiController] attribute. 下列範例顯示自訂基類,以及衍生自該類別的控制器:The following example shows a custom base class and a controller that derives from it:

[ApiController]
public class MyControllerBase : ControllerBase
{
}
[Produces(MediaTypeNames.Application.Json)]
[Route("[controller]")]
public class PetsController : MyControllerBase
[Produces(MediaTypeNames.Application.Json)]
[Route("api/[controller]")]
public class PetsController : MyControllerBase

元件上的屬性Attribute on an assembly

如果相容性版本設定為 2.2 或更新版本,[ApiController] 屬性就可以套用至組件。If compatibility version is set to 2.2 or later, the [ApiController] attribute can be applied to an assembly. 以這種方式標註會將 Web API 行為套用至組件中的所有控制器。Annotation in this manner applies web API behavior to all controllers in the assembly. 沒有任何方法可以退出個別控制器。There's no way to opt out for individual controllers. 將元件層級屬性套用至類別周圍的命名空間宣告 StartupApply the assembly-level attribute to the namespace declaration surrounding the Startup class:

[assembly: ApiController]
namespace WebApiSample
{
    public class Startup
    {
        ...
    }
}

屬性路由需求Attribute routing requirement

[ApiController] 屬性會讓屬性路由需求。The [ApiController] attribute makes attribute routing a requirement. 例如:For example:

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase

無法透過 UseEndpointsUseMvcUseMvcWithDefaultRoute 在中定義的傳統路由來存取動作 Startup.ConfigureActions are inaccessible via conventional routes defined by UseEndpoints, UseMvc, or UseMvcWithDefaultRoute in Startup.Configure.

[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase

無法透過 UseMvc 中所定義的慣例路由Startup.Configure 中的 UseMvcWithDefaultRoute 來存取動作。Actions are inaccessible via conventional routes defined by UseMvc or UseMvcWithDefaultRoute in Startup.Configure.

HTTP 400 自動回應Automatic HTTP 400 responses

[ApiController] 屬性會讓模型驗證錯誤自動觸發 HTTP 400 回應。The [ApiController] attribute makes model validation errors automatically trigger an HTTP 400 response. 因此,動作方法不再需要下列程式碼:Consequently, the following code is unnecessary in an action method:

if (!ModelState.IsValid)
{
    return BadRequest(ModelState);
}

ASP.NET Core MVC 會使用 ModelStateInvalidFilter 動作篩選準則來執行上述檢查。ASP.NET Core MVC uses the ModelStateInvalidFilter action filter to do the preceding check.

預設 BadRequest 回應Default BadRequest response

使用相容性版本2.1 時,HTTP 400 回應的預設回應類型為 SerializableErrorWith a compatibility version of 2.1, the default response type for an HTTP 400 response is SerializableError. 下列要求主體是序列化型別的範例:The following request body is an example of the serialized type:

{
  "": [
    "A non-empty request body is required."
  ]
}

當相容性版本為2.2 或更新版本時,HTTP 400 回應的預設回應類型為 ValidationProblemDetailsWith a compatibility version of 2.2 or later, the default response type for an HTTP 400 response is ValidationProblemDetails. 下列要求主體是序列化型別的範例:The following request body is an example of the serialized type:

{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "|7fb5e16a-4c8f23bbfc974667.",
  "errors": {
    "": [
      "A non-empty request body is required."
    ]
  }
}

ValidationProblemDetails類型:The ValidationProblemDetails type:

  • 提供機器可讀取的格式來指定 web API 回應中的錯誤。Provides a machine-readable format for specifying errors in web API responses.
  • 符合 RFC 7807 規格Complies with the RFC 7807 specification.

若要讓自動和自訂回應保持一致,請呼叫 ValidationProblem 方法,而不是 BadRequestTo make automatic and custom responses consistent, call the ValidationProblem method instead of BadRequest. ValidationProblem 傳回 ValidationProblemDetails 物件以及自動回應。ValidationProblem returns a ValidationProblemDetails object as well as the automatic response.

記錄自動 400 回應Log automatic 400 responses

請參閱 如何記錄模型驗證錯誤的自動400回應 (dotnet/AspNetCore.Docs # 12157) See How to log automatic 400 responses on model validation errors (dotnet/AspNetCore.Docs#12157).

停用自動400回應Disable automatic 400 response

若要停用自動 400 行為,請將 SuppressModelStateInvalidFilter 屬性設定為 trueTo disable the automatic 400 behavior, set the SuppressModelStateInvalidFilter property to true. Startup.ConfigureServices 中新增下列醒目提示的程式碼:Add the following highlighted code in Startup.ConfigureServices:

services.AddControllers()
    .ConfigureApiBehaviorOptions(options =>
    {
        options.SuppressConsumesConstraintForFormFileParameters = true;
        options.SuppressInferBindingSourcesForParameters = true;
        options.SuppressModelStateInvalidFilter = true;
        options.SuppressMapClientErrors = true;
        options.ClientErrorMapping[StatusCodes.Status404NotFound].Link =
            "https://httpstatuses.com/404";
    });
services.AddMvc()
    .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
    .ConfigureApiBehaviorOptions(options =>
    {
        options.SuppressConsumesConstraintForFormFileParameters = true;
        options.SuppressInferBindingSourcesForParameters = true;
        options.SuppressModelStateInvalidFilter = true;
        options.SuppressMapClientErrors = true;
        options.ClientErrorMapping[404].Link =
            "https://httpstatuses.com/404";
    });
services.Configure<ApiBehaviorOptions>(options =>
{
    options.SuppressConsumesConstraintForFormFileParameters = true;
    options.SuppressInferBindingSourcesForParameters = true;
    options.SuppressModelStateInvalidFilter = true;
});

繫結來源參數推斷Binding source parameter inference

繫結來源屬性可定義動作參數值的所在位置。A binding source attribute defines the location at which an action parameter's value is found. 系統提供下列繫結來源屬性:The following binding source attributes exist:

屬性Attribute 繫結來源Binding source
[FromBody] 要求本文Request body
[FromForm] 要求本文中的表單資料Form data in the request body
[FromHeader] 要求標頭Request header
[FromQuery] 要求查詢字串參數Request query string parameter
[FromRoute] 來自目前要求的路由資料Route data from the current request
[FromServices] 作為動作參數插入的要求服務The request service injected as an action parameter

警告

當值可能包含 %2f (也就是 /) 時,請勿使用 [FromRoute]Don't use [FromRoute] when values might contain %2f (that is /). %2f 不會是未逸出的 /%2f won't be unescaped to /. 如果值可能包含 %2f,請使用 [FromQuery]Use [FromQuery] if the value might contain %2f.

若沒有 [ApiController] 屬性或繫結來源屬性 (例如 [FromQuery]),ASP.NET Core 執行階段會嘗試使用複雜物件模型繫結器。Without the [ApiController] attribute or binding source attributes like [FromQuery], the ASP.NET Core runtime attempts to use the complex object model binder. 複雜物件模型繫結器會以定義的順序從值提供者提取資料。The complex object model binder pulls data from value providers in a defined order.

在下列範例中,[FromQuery] 屬性表示 discontinuedOnly 參數值是在要求 URL 查詢字串中提供:In the following example, the [FromQuery] attribute indicates that the discontinuedOnly parameter value is provided in the request URL's query string:

[HttpGet]
public ActionResult<List<Product>> Get(
    [FromQuery] bool discontinuedOnly = false)
{
    List<Product> products = null;

    if (discontinuedOnly)
    {
        products = _productsInMemoryStore.Where(p => p.IsDiscontinued).ToList();
    }
    else
    {
        products = _productsInMemoryStore;
    }

    return products;
}

[ApiController] 屬性會依據動作參數的預設資料來源套用推斷規則。The [ApiController] attribute applies inference rules for the default data sources of action parameters. 這些規則透過將屬性套用至動作參數,讓您不必以手動方式識別的繫結來源。These rules save you from having to identify binding sources manually by applying attributes to the action parameters. 繫結來源推斷規則的行為如下所示:The binding source inference rules behave as follows:

  • 系統會依據複雜類型參數推斷 [FromBody][FromBody] is inferred for complex type parameters. 如果是任何具有像是 IFormCollectionCancellationToken 等特殊意義的複雜內建類型,則為 [FromBody] 推斷規則的例外。An exception to the [FromBody] inference rule is any complex, built-in type with a special meaning, such as IFormCollection and CancellationToken. 繫結來源推斷程式碼會忽略這些特殊的類型。The binding source inference code ignores those special types.
  • [FromForm] 針對類型 IFormFileIFormFileCollection 的動作參數推斷的。[FromForm] is inferred for action parameters of type IFormFile and IFormFileCollection. 而不會依據任何簡單或使用者定義的類型進行推斷。It's not inferred for any simple or user-defined types.
  • 系統會依據符合路由範本參數的任何動作參數名稱推斷 [FromRoute][FromRoute] is inferred for any action parameter name matching a parameter in the route template. 如果有多個路由符合動作參數,則會將任何路由值視為 [FromRoute]When more than one route matches an action parameter, any route value is considered [FromRoute].
  • 系統會依據任何其他動作參數推斷 [FromQuery][FromQuery] is inferred for any other action parameters.

FromBody 推斷備註FromBody inference notes

並不會為像是 stringint 等簡單型別,推斷 [FromBody][FromBody] isn't inferred for simple types such as string or int. 因此,當需要使用該功能時,應為簡單型別使用 [FromBody] 屬性。Therefore, the [FromBody] attribute should be used for simple types when that functionality is needed.

當動作有多個參數從要求主體繫結時,會擲回例外狀況。When an action has more than one parameter bound from the request body, an exception is thrown. 例如,下列所有動作方法簽章都會造成例外狀況:For example, all of the following action method signatures cause an exception:

  • 因兩個參數都是複雜類型,而推斷 [FromBody][FromBody] inferred on both because they're complex types.

    [HttpPost]
    public IActionResult Action1(Product product, Order order)
    
  • 因為其為複雜類型,所以一個有 [FromBody] 屬性,而推斷另一個。[FromBody] attribute on one, inferred on the other because it's a complex type.

    [HttpPost]
    public IActionResult Action2(Product product, [FromBody] Order order)
    
  • 兩者均有 [FromBody] 屬性。[FromBody] attribute on both.

    [HttpPost]
    public IActionResult Action3([FromBody] Product product, [FromBody] Order order)
    

注意

在 ASP.NET Core 2.1 中,集合類型參數 (例如清單與陣列) 不正確地推斷為 [FromQuery]In ASP.NET Core 2.1, collection type parameters such as lists and arrays are incorrectly inferred as [FromQuery]. [FromBody] 屬性應該用於這些參數 (若它們將從要求本文繫結)。The [FromBody] attribute should be used for these parameters if they are to be bound from the request body. 此行為在 ASP.NET Core 2.2 或更新版本中已修正,其中集合類型參數預設推斷為從本文繫結。This behavior is corrected in ASP.NET Core 2.2 or later, where collection type parameters are inferred to be bound from the body by default.

停用推斷規則Disable inference rules

若要停用繫結來源推斷,請將 SuppressInferBindingSourcesForParameters 設定為 trueTo disable binding source inference, set SuppressInferBindingSourcesForParameters to true. 將下列程式碼加入 Startup.ConfigureServicesAdd the following code in Startup.ConfigureServices:

services.AddControllers()
    .ConfigureApiBehaviorOptions(options =>
    {
        options.SuppressConsumesConstraintForFormFileParameters = true;
        options.SuppressInferBindingSourcesForParameters = true;
        options.SuppressModelStateInvalidFilter = true;
        options.SuppressMapClientErrors = true;
        options.ClientErrorMapping[StatusCodes.Status404NotFound].Link =
            "https://httpstatuses.com/404";
    });
services.AddMvc()
    .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
    .ConfigureApiBehaviorOptions(options =>
    {
        options.SuppressConsumesConstraintForFormFileParameters = true;
        options.SuppressInferBindingSourcesForParameters = true;
        options.SuppressModelStateInvalidFilter = true;
        options.SuppressMapClientErrors = true;
        options.ClientErrorMapping[404].Link =
            "https://httpstatuses.com/404";
    });
services.Configure<ApiBehaviorOptions>(options =>
{
    options.SuppressConsumesConstraintForFormFileParameters = true;
    options.SuppressInferBindingSourcesForParameters = true;
    options.SuppressModelStateInvalidFilter = true;
});

多部分/表單資料要求推斷Multipart/form-data request inference

[ApiController]當動作參數以屬性標注時,屬性會套用推斷規則 [FromForm]The [ApiController] attribute applies an inference rule when an action parameter is annotated with the [FromForm] attribute. multipart/form-data會推斷要求內容類型。The multipart/form-data request content type is inferred.

若要停用預設行為,請將 SuppressConsumesConstraintForFormFileParameters 屬性設定為 true Startup.ConfigureServicesTo disable the default behavior, set the SuppressConsumesConstraintForFormFileParameters property to true in Startup.ConfigureServices:

services.AddControllers()
    .ConfigureApiBehaviorOptions(options =>
    {
        options.SuppressConsumesConstraintForFormFileParameters = true;
        options.SuppressInferBindingSourcesForParameters = true;
        options.SuppressModelStateInvalidFilter = true;
        options.SuppressMapClientErrors = true;
        options.ClientErrorMapping[StatusCodes.Status404NotFound].Link =
            "https://httpstatuses.com/404";
    });
services.AddMvc()
    .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
    .ConfigureApiBehaviorOptions(options =>
    {
        options.SuppressConsumesConstraintForFormFileParameters = true;
        options.SuppressInferBindingSourcesForParameters = true;
        options.SuppressModelStateInvalidFilter = true;
        options.SuppressMapClientErrors = true;
        options.ClientErrorMapping[404].Link =
            "https://httpstatuses.com/404";
    });
services.Configure<ApiBehaviorOptions>(options =>
{
    options.SuppressConsumesConstraintForFormFileParameters = true;
    options.SuppressInferBindingSourcesForParameters = true;
    options.SuppressModelStateInvalidFilter = true;
});

錯誤狀態碼的問題詳細資料Problem details for error status codes

當相容性版本為 2.2 或更新版本時,MVC 會將錯誤結果 (具有狀態碼 400 以上的結果) 為具有 ProblemDetails 的結果。When the compatibility version is 2.2 or later, MVC transforms an error result (a result with status code 400 or higher) to a result with ProblemDetails. RFC 7807 規格為基礎的 ProblemDetails 類型,在 HTTP 回應中提供電腦可讀取的錯誤詳細資料。The ProblemDetails type is based on the RFC 7807 specification for providing machine-readable error details in an HTTP response.

請考慮下列控制器動作中的程式碼:Consider the following code in a controller action:

if (pet == null)
{
    return NotFound();
}

NotFound方法會產生具有主體的 HTTP 404 狀態碼 ProblemDetailsThe NotFound method produces an HTTP 404 status code with a ProblemDetails body. 例如:For example:

{
  type: "https://tools.ietf.org/html/rfc7231#section-6.5.4",
  title: "Not Found",
  status: 404,
  traceId: "0HLHLV31KRN83:00000001"
}

停用 ProblemDetails 回應Disable ProblemDetails response

ProblemDetails當屬性設定為時,會停用自動建立 for 錯誤狀態碼 SuppressMapClientErrors trueThe automatic creation of a ProblemDetails for error status codes is disabled when the SuppressMapClientErrors property is set to true. 將下列程式碼加入 Startup.ConfigureServicesAdd the following code in Startup.ConfigureServices:

services.AddControllers()
    .ConfigureApiBehaviorOptions(options =>
    {
        options.SuppressConsumesConstraintForFormFileParameters = true;
        options.SuppressInferBindingSourcesForParameters = true;
        options.SuppressModelStateInvalidFilter = true;
        options.SuppressMapClientErrors = true;
        options.ClientErrorMapping[StatusCodes.Status404NotFound].Link =
            "https://httpstatuses.com/404";
    });
services.AddMvc()
    .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
    .ConfigureApiBehaviorOptions(options =>
    {
        options.SuppressConsumesConstraintForFormFileParameters = true;
        options.SuppressInferBindingSourcesForParameters = true;
        options.SuppressModelStateInvalidFilter = true;
        options.SuppressMapClientErrors = true;
        options.ClientErrorMapping[404].Link =
            "https://httpstatuses.com/404";
    });

使用 [使用] 屬性定義支援的要求內容類型Define supported request content types with the [Consumes] attribute

依預設,動作支援所有可用的要求內容類型。By default, an action supports all available request content types. 例如,如果將應用程式設定為支援 JSON 和 XML 輸入格式器,則動作支援多種內容類型,包括 application/jsonapplication/xmlFor example, if an app is configured to support both JSON and XML input formatters, an action supports multiple content types, including application/json and application/xml.

[取用]屬性允許動作限制支援的要求內容類型。The [Consumes] attribute allows an action to limit the supported request content types. [Consumes] 屬性套用至動作或控制器,並指定一或多個內容類型:Apply the [Consumes] attribute to an action or controller, specifying one or more content types:

[HttpPost]
[Consumes("application/xml")]
public IActionResult CreateProduct(Product product)

在上述程式碼中, CreateProduct 動作會指定內容類型 application/xmlIn the preceding code, the CreateProduct action specifies the content type application/xml. 路由至此動作的要求必須指定的 Content-Type 標頭 application/xmlRequests routed to this action must specify a Content-Type header of application/xml. 未指定 Content-Type 標頭的要求會 application/xml415 不支援的媒體類型 回應中指定結果。Requests that don't specify a Content-Type header of application/xml result in a 415 Unsupported Media Type response.

[Consumes]屬性也可讓動作根據傳入要求的內容類型,藉由套用類型條件約束來影響其選取專案。The [Consumes] attribute also allows an action to influence its selection based on an incoming request's content type by applying a type constraint. 請考慮下列範例:Consider the following example:

[ApiController]
[Route("api/[controller]")]
public class ConsumesController : ControllerBase
{
    [HttpPost]
    [Consumes("application/json")]
    public IActionResult PostJson(IEnumerable<int> values) =>
        Ok(new { Consumes = "application/json", Values = values });

    [HttpPost]
    [Consumes("application/x-www-form-urlencoded")]
    public IActionResult PostForm([FromForm] IEnumerable<int> values) =>
        Ok(new { Consumes = "application/x-www-form-urlencoded", Values = values });
}

在上述程式碼中, ConsumesController 會設定來處理傳送至 URL 的要求 https://localhost:5001/api/ConsumesIn the preceding code, ConsumesController is configured to handle requests sent to the https://localhost:5001/api/Consumes URL. 控制器的兩個動作和都 PostJson PostForm 處理具有相同 URL 的 POST 要求。Both of the controller's actions, PostJson and PostForm, handle POST requests with the same URL. 如果沒有套用 [Consumes] 類型條件約束的屬性,則會擲回不明確的 match 例外狀況。Without the [Consumes] attribute applying a type constraint, an ambiguous match exception is thrown.

[Consumes]屬性會套用至這兩個動作。The [Consumes] attribute is applied to both actions. PostJson動作會處理與 Content-Type 標頭一起傳送的要求 application/jsonThe PostJson action handles requests sent with a Content-Type header of application/json. PostForm動作會處理與 Content-Type 標頭一起傳送的要求 application/x-www-form-urlencodedThe PostForm action handles requests sent with a Content-Type header of application/x-www-form-urlencoded.

其他資源Additional resources