ASP.NET Core 中的資料繫結Model Binding in ASP.NET Core

本文會說明何謂模型繫結、其運作方式,以及如何自訂其行為。This article explains what model binding is, how it works, and how to customize its behavior.

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

何謂模型繫結What is Model binding

控制器和 Razor Pages 使用來自 HTTP 要求的資料。Controllers and Razor pages work with data that comes from HTTP requests. 例如,路由資料可能會提供記錄索引鍵,而已張貼的表單欄位可能會提供模型屬性的值。For example, route data may provide a record key, and posted form fields may provide values for the properties of the model. 撰寫程式碼來擷取這些值的每一個並將它們從字串轉換成 .NET 類型,不但繁瑣又容易發生錯誤。Writing code to retrieve each of these values and convert them from strings to .NET types would be tedious and error-prone. 模型繫結會自動化此程序。Model binding automates this process. 模型繫結系統:The model binding system:

  • 擷取來自各種來源的資料,例如路由資料、表單欄位和查詢字串。Retrieves data from various sources such as route data, form fields, and query strings.
  • 在方法參數和公用屬性中,將資料提供給控制器和 Razor Pages。Provides the data to controllers and Razor pages in method parameters and public properties.
  • 將字串資料轉換成 .NET 類型。Converts string data to .NET types.
  • 更新複雜類型的屬性。Updates properties of complex types.

範例Example

假設您有下列動作方法:Suppose you have the following action method:

[HttpGet("{id}")]
public ActionResult<Pet> GetById(int id, bool dogsOnly)

而應用程式收到具有此 URL 的要求:And the app receives a request with this URL:

http://contoso.com/api/pets/2?DogsOnly=true

在路由系統選取動作方法之後,模型繫結會透過下列步驟:Model binding goes though the following steps after the routing system selects the action method:

  • 尋找第一個參數 GetByID,它是名為 id 的整數。Finds the first parameter of GetByID, an integer named id.
  • 查看 HTTP 要求中所有可用的來源,在路由資料中找到 id = "2"。Looks through the available sources in the HTTP request and finds id = "2" in route data.
  • 將字串 "2" 轉換成整數 2。Converts the string "2" into integer 2.
  • 尋找下一個 GetByID 的參數,它是名為 dogsOnly 的布林值。Finds the next parameter of GetByID, a boolean named dogsOnly.
  • 查看來源,在查詢字串中找到 "DogsOnly=true"。Looks through the sources and finds "DogsOnly=true" in the query string. 名稱比對不區分大小寫。Name matching is not case-sensitive.
  • 將字串 "true" 轉換成布林值 trueConverts the string "true" into boolean true.

架構接著會呼叫 GetById 方法,針對 id 參數傳送 2、dogsOnly 參數傳送 trueThe framework then calls the GetById method, passing in 2 for the id parameter, and true for the dogsOnly parameter.

在上例中,模型繫結目標都是簡單型別的方法參數。In the preceding example, the model binding targets are method parameters that are simple types. 目標也可能是複雜類型的屬性。Targets may also be the properties of a complex type. 成功繫結每一個屬性後,該屬性就會發生模型驗證After each property is successfully bound, model validation occurs for that property. 哪些資料繫結至模型,以及任何繫結或驗證錯誤的記錄,都會儲存在 ControllerBase.ModelStatePageModel.ModelStateThe record of what data is bound to the model, and any binding or validation errors, is stored in ControllerBase.ModelState or PageModel.ModelState. 為了解此程序是否成功,應用程式會檢查 ModelState.IsValid 旗標。To find out if this process was successful, the app checks the ModelState.IsValid flag.

目標Targets

模型繫結會嘗試尋找下列幾種目標的值:Model binding tries to find values for the following kinds of targets:

  • 要求路由目標的控制器動作方法參數。Parameters of the controller action method that a request is routed to.
  • 路由要求之目標 Razor Pages 處理常式方法的參數。Parameters of the Razor Pages handler method that a request is routed to.
  • 控制站的公用屬性或 PageModel 類別,如由屬性指定。Public properties of a controller or PageModel class, if specified by attributes.

[BindProperty] 屬性[BindProperty] attribute

可以套用至控制器公用屬性或 PageModel 類別,讓模型繫結以該屬性為目標:Can be applied to a public property of a controller or PageModel class to cause model binding to target that property:

public class EditModel : InstructorsPageModel
{
    public EditModel() : base()
    {
    }

    [BindProperty]
    public Instructor Instructor { get; set; }

[BindProperties] 屬性[BindProperties] attribute

支援 ASP.NET Core 2.1 和更新版本。Available in ASP.NET Core 2.1 and later. 可以套用至控制器或 PageModel 類別,通知模型繫結以該類別的所有公用屬性為目標:Can be applied to a controller or PageModel class to tell model binding to target all public properties of the class:

[BindProperties(SupportsGet=true)]
public class CreateModel : InstructorsPageModel
{
    public CreateModel() : base()
    {
    }

    public Instructor Instructor { get; set; }

適用於 HTTP GET 要求的模型繫結Model binding for HTTP GET requests

根據預設,屬性不會針對 HTTP GET 要求繫結。By default, properties are not bound for HTTP GET requests. 一般而言,GET 要求只需要記錄識別碼參數。Typically, all you need for a GET request is a record ID parameter. 此記錄識別碼用來查詢資料庫中的項目。The record ID is used to look up the item in the database. 因此,不需要繫結保留模型執行個體的屬性。Therefore, there is no need to bind a property that holds an instance of the model. 在您要從 GET 要求將屬性繫結至資料的案例中,請將 SupportsGet 屬性設為 trueIn scenarios where you do want properties bound to data from GET requests, set the SupportsGet property to true:

[BindProperty(Name ="ai_user", SupportsGet = true)]
public string ApplicationInsightsCookie { get; set; }

來源Sources

根據預設,模型繫結會從下列 HTTP 要求的來源中,取得索引鍵/值組形式的資料:By default, model binding gets data in the form of key-value pairs from the following sources in an HTTP request:

  1. 表單欄位Form fields
  2. 要求本文 (適用於具有 [ApiController] 屬性的控制器。)The request body (For controllers that have the [ApiController] attribute.)
  3. 路由資料Route data
  4. 查詢字串參數Query string parameters
  5. 已上傳的檔案Uploaded files

針對每個目標參數或屬性,會依照本清單顯示的順序掃描來源。For each target parameter or property, the sources are scanned in the order indicated in this list. 但也有一些例外:There are a few exceptions:

  • 路由資料和查詢字串值只用於簡單型別。Route data and query string values are used only for simple types.
  • 所上傳檔案只會繫結至實作 IFormFileIEnumerable<IFormFile> 的目標類型。Uploaded files are bound only to target types that implement IFormFile or IEnumerable<IFormFile>.

如果預設行為不提供正確的結果,您可以使用下列其中一個屬性來指定用於任何所指定目標的來源。If the default behavior doesn't give the right results, you can use one of the following attributes to specify the source to use for any given target.

這些屬性:These attributes:

  • 會個別新增至模型屬性 (不是模型類別),如下列範例所示:Are added to model properties individually (not to the model class), as in the following example:

    public class Instructor
    {
        public int ID { get; set; }
    
        [FromQuery(Name ="Note")]
        public string NoteFromQueryString { get; set; }
    
  • 選擇性地接受建構函式中的模型名稱值。Optionally accept a model name value in the constructor. 如果屬性名稱不符合要求中的值,則提供此選項。This option is provided in case the property name doesn't match the value in the request. 例如,要求中的值可能是名稱中有連字號的標頭,如下列範例所示:For instance, the value in the request might be a header with a hyphen in its name, as in the following example:

    public void OnGet([FromHeader(Name="Accept-Language")] string language)
    

[FromBody] 屬性[FromBody] attribute

要求本文資料會使用要求內容類型特定的輸入格式器來剖析。The request body data is parsed by using input formatters specific to the content type of the request. 本文稍後會說明輸入格式器。Input formatters are explained later in this article.

針對每個動作方法,請不要將 [FromBody] 套用至多個參數。Don't apply [FromBody] to more than one parameter per action method. ASP.NET Core 執行階段會將讀取要求資料流的責任委派給輸入格式器。The ASP.NET Core runtime delegates the responsibility of reading the request stream to the input formatter. 要求資料經讀取後,即無法再次讀取以用來繫結其他 [FromBody] 參數。Once the request stream is read, it's no longer available to be read again for binding other [FromBody] parameters.

其他來源Additional sources

來源資料由「值提供者」 提供給模型繫結系統。Source data is provided to the model binding system by value providers. 您可以撰寫並註冊自訂值提供者,其從其他來源取得模型繫結資料。You can write and register custom value providers that get data for model binding from other sources. 例如,您可能想要 Cookie 或工作階段狀態的資料。For example, you might want data from cookies or session state. 從新來源取得資料:To get data from a new source:

  • 建立會實作 IValueProvider 的類別。Create a class that implements IValueProvider.
  • 建立會實作 IValueProviderFactory 的類別。Create a class that implements IValueProviderFactory.
  • Startup.ConfigureServices 中註冊 Factory 類別。Register the factory class in Startup.ConfigureServices.

範例應用程式包含值提供者和從 Cookie 取得值的 actory 範例。The sample app includes a value provider and factory example that gets values from cookies. 以下是 Startup.ConfigureServices 中的註冊碼:Here's the registration code in Startup.ConfigureServices:

services.AddMvc(options =>
{
    options.ValueProviderFactories.Add(new CookieValueProviderFactory());
    options.ModelMetadataDetailsProviders.Add(
        new ExcludeBindingMetadataProvider(typeof(System.Version)));
    options.ModelMetadataDetailsProviders.Add(
        new SuppressChildValidationMetadataProvider(typeof(System.Guid)));
})
.AddXmlSerializerFormatters()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

顯示的程式碼會將自訂值提供者放在所有內建值提供者的後面。The code shown puts the custom value provider after all the built-in value providers. 若要讓它在清單中排位第一,請呼叫 Insert(0, new CookieValueProviderFactory()) 而非 AddTo make it the first in the list, call Insert(0, new CookieValueProviderFactory()) instead of Add.

無模型屬性的來源No source for a model property

根據預設,如果找不到模型屬性值,就不會建立模型狀態錯誤。By default, a model state error isn't created if no value is found for a model property. 屬性設定為 null 或預設值:The property is set to null or a default value:

  • 可為 Null 的簡單型別會設為 nullNullable simple types are set to null.
  • 不可為 Null 的實值型別會設為 default(T)Non-nullable value types are set to default(T). 例如,參數 int id 設為 0。For example, a parameter int id is set to 0.
  • 針對複雜類型,模型繫結會使用預設建構函式建立執行個體,但不設定屬性。For complex Types, model binding creates an instance by using the default constructor, without setting properties.
  • 陣列設為 Array.Empty<T>(),但 byte[] 陣列設為 nullArrays are set to Array.Empty<T>(), except that byte[] arrays are set to null.

如果模型狀態在模型屬性表單欄位中找不到任何項目時應該失效,則請使用 [BindRequired] 屬性If model state should be invalidated when nothing is found in form fields for a model property, use the [BindRequired] attribute.

請注意,此 [BindRequired] 行為適用於來自已張貼表單資料的模型繫結,不適合要求本文中的 JSON 或 XML 資料。Note that this [BindRequired] behavior applies to model binding from posted form data, not to JSON or XML data in a request body. 要求本文資料由輸入格式器處理。Request body data is handled by input formatters.

類型轉換錯誤Type conversion errors

如果找到來源,但無法轉換成目標型別,則模型狀態會標記為無效。If a source is found but can't be converted into the target type, model state is flagged as invalid. 目標參數或屬性會設為 null 或預設值,如上一節中所述。The target parameter or property is set to null or a default value, as noted in the previous section.

在具有 [ApiController] 屬性的 API 控制器中,無效的模型狀態會導致自動 HTTP 400 回應。In an API controller that has the [ApiController] attribute, invalid model state results in an automatic HTTP 400 response.

在 Razor 頁面中,重新顯示有錯誤訊息的頁面:In a Razor page, redisplay the page with an error message:

public IActionResult OnPost()
{
    if (!ModelState.IsValid)
    {
        return Page();
    }

    _instructorsInMemoryStore.Add(Instructor);
    return RedirectToPage("./Index");
}

用戶端驗證會攔截大部分不正確的資料,否則會被提交至 Razor Pages 表單。Client-side validation catches most bad data that would otherwise be submitted to a Razor Pages form. 此驗證會讓您更難觸發上述醒目提示的程式碼。This validation makes it hard to trigger the preceding highlighted code. 範例應用程式包含 [Submit with Invalid Date] (以無效日期送出) 按鈕,將不正確的資料放入 [雇用日期] 欄位並提交表單。The sample app includes a Submit with Invalid Date button that puts bad data in the Hire Date field and submits the form. 此按鈕會顯示當資料轉換錯誤發生時,重新顯示頁面的程式碼如何運作。This button shows how the code for redisplaying the page works when data conversion errors occur.

當上述程式碼重新顯示頁面時,無效的輸入不會顯示在表單欄位中。When the page is redisplayed by the preceding code, the invalid input is not shown in the form field. 這是因為模型屬性已設為 null 或預設值。This is because the model property has been set to null or a default value. 無效的輸入確實會出現在錯誤訊息中。The invalid input does appear in an error message. 但是,如果您想要在表單欄位中重新顯示不正確的資料,請考慮讓模型屬性成為字串,以手動方式執行資料轉換。But if you want to redisplay the bad data in the form field, consider making the model property a string and doing the data conversion manually.

如果您不希望類型轉換錯誤導致模型狀態錯誤,建議使用相同的策略。The same strategy is recommended if you don't want type conversion errors to result in model state errors. 在此情況下,讓模型屬性成為字串。In that case, make the model property a string.

簡單型別Simple types

模型繫結器可將來源字串轉換成的簡單型別包括:The simple types that the model binder can convert source strings into include the following:

複雜類型Complex types

複雜類型必須具有要繫結的公用預設建構函式及公用可寫入屬性。A complex type must have a public default constructor and public writable properties to bind. 發生模型繫結時,類別會使用公用預設建構函式具現化。When model binding occurs, the class is instantiated using the public default constructor.

針對複雜類型的每個屬性,模型繫結會查看名稱模式 prefix.property_name 的來源。For each property of the complex type, model binding looks through the sources for the name pattern prefix.property_name. 如果找不到,它會只尋找沒有前置詞的 property_nameIf nothing is found, it looks for just property_name without the prefix.

若要繫結至參數,則前置詞是參數名稱。For binding to a parameter, the prefix is the parameter name. 若要繫結至 PageModel 公用屬性,則前置詞為公用屬性名稱。For binding to a PageModel public property, the prefix is the public property name. 某些屬性 (Attribute) 具有 Prefix 屬性 (Property),其可讓您覆寫參數或屬性名稱的預設使用方法。Some attributes have a Prefix property that lets you override the default usage of parameter or property name.

例如,假設複雜類型是下列 Instructor 類別:For example, suppose the complex type is the following Instructor class:

public class Instructor
{
    public int ID { get; set; }
    public string LastName { get; set; }
    public string FirstName { get; set; }
}

前置詞 = 參數名稱Prefix = parameter name

如果要繫結的模型是名為 instructorToUpdate 的參數:If the model to be bound is a parameter named instructorToUpdate:

public IActionResult OnPost(int? id, Instructor instructorToUpdate)

模型繫結從查看索引鍵 instructorToUpdate.ID 的來源開始。Model binding starts by looking through the sources for the key instructorToUpdate.ID. 如果找不到,則它會尋找不含前置詞的 IDIf that isn't found, it looks for ID without a prefix.

前置詞 = 屬性名稱Prefix = property name

如果要繫結的模型是控制器或 PageModel 類別名為 Instructor 的屬性:If the model to be bound is a property named Instructor of the controller or PageModel class:

[BindProperty]
public Instructor Instructor { get; set; }

模型繫結從查看索引鍵 Instructor.ID 的來源開始。Model binding starts by looking through the sources for the key Instructor.ID. 如果找不到,則它會尋找不含前置詞的 IDIf that isn't found, it looks for ID without a prefix.

自訂前置詞Custom prefix

如果要繫結的模型是名為 instructorToUpdate 的參數,且 Bind 屬性指定 Instructor 為前置詞:If the model to be bound is a parameter named instructorToUpdate and a Bind attribute specifies Instructor as the prefix:

public IActionResult OnPost(
    int? id, [Bind(Prefix = "Instructor")] Instructor instructorToUpdate)

模型繫結從查看索引鍵 Instructor.ID 的來源開始。Model binding starts by looking through the sources for the key Instructor.ID. 如果找不到,則它會尋找不含前置詞的 IDIf that isn't found, it looks for ID without a prefix.

複雜類型目標的屬性Attributes for complex type targets

有數個內建屬性可供控制複雜類型的模型繫結:Several built-in attributes are available for controlling model binding of complex types:

  • [BindRequired]
  • [BindNever]
  • [Bind]

注意

當張貼的表單資料為值來源時,這些屬性會影響模型繫結。These attributes affect model binding when posted form data is the source of values. 它們不會影響處理已張貼 JSON 和 XML 要求本文的輸入格式器。They do not affect input formatters, which process posted JSON and XML request bodies. 本文稍後會說明輸入格式器。Input formatters are explained later in this article.

另請參閱模型驗證中的 [Required] 屬性討論。See also the discussion of the [Required] attribute in Model validation.

[BindRequired] 屬性[BindRequired] attribute

只能套用至模型屬性,不能套用到方法參數。Can only be applied to model properties, not to method parameters. 如果模型的屬性不能發生繫結,則會造成模型繫結新增模型狀態錯誤。Causes model binding to add a model state error if binding cannot occur for a model's property. 以下為範例:Here's an example:

public class InstructorWithCollection
{
    public int ID { get; set; }

    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    [Display(Name = "Hire Date")]
    [BindRequired]
    public DateTime HireDate { get; set; }

[BindNever] 屬性[BindNever] attribute

只能套用至模型屬性,不能套用到方法參數。Can only be applied to model properties, not to method parameters. 避免模型繫結設定模型的屬性。Prevents model binding from setting a model's property. 以下為範例:Here's an example:

public class InstructorWithDictionary
{
    [BindNever]
    public int ID { get; set; }

[Bind] 屬性[Bind] attribute

可以套用至類別或方法參數。Can be applied to a class or a method parameter. 指定模型繫結應包含哪些模型屬性。Specifies which properties of a model should be included in model binding.

在下列範例中,當呼叫任何處理常式或動作方法時,只會繫結 Instructor 模型的指定屬性:In the following example, only the specified properties of the Instructor model are bound when any handler or action method is called:

[Bind("LastName,FirstMidName,HireDate")]
public class Instructor

在下列範例中,當呼叫 OnPost 方法時,只會繫結 Instructor 模型的指定屬性:In the following example, only the specified properties of the Instructor model are bound when the OnPost method is called:

[HttpPost]
public IActionResult OnPost([Bind("LastName,FirstMidName,HireDate")] Instructor instructor)

[Bind] 屬性可用來防止「建立」 案例中的大量指派。The [Bind] attribute can be used to protect against overposting in create scenarios. 它在編輯案例中運作不良,因為排除的屬性都設定為 null 或預設值,而非保持不變。It doesn't work well in edit scenarios because excluded properties are set to null or a default value instead of being left unchanged. 建議使用檢視模型而非 [Bind] 屬性來防禦大量指派。For defense against overposting, view models are recommended rather than the [Bind] attribute. 如需詳細資訊,請參閱關於大量指派的安全性注意事項For more information, see Security note about overposting.

集合Collections

針對簡單型別集合的目標,模型繫結會尋找符合 parameter_nameproperty_name 的項目。For targets that are collections of simple types, model binding looks for matches to parameter_name or property_name. 如果找不到相符項目,它會尋找其中一種沒有前置詞的受支援格式。If no match is found, it looks for one of the supported formats without the prefix. 例如:For example:

  • 假設要繫結的參數是名為 selectedCourses 的陣列:Suppose the parameter to be bound is an array named selectedCourses:

    public IActionResult OnPost(int? id, int[] selectedCourses)
    
  • 表單或查詢字串資料可以是下列其中一種格式:Form or query string data can be in one of the following formats:

    selectedCourses=1050&selectedCourses=2000 
    
    selectedCourses[0]=1050&selectedCourses[1]=2000
    
    [0]=1050&[1]=2000
    
    selectedCourses[a]=1050&selectedCourses[b]=2000&selectedCourses.index=a&selectedCourses.index=b
    
    [a]=1050&[b]=2000&index=a&index=b
    
  • 只有表單資料支援下列格式:The following format is supported only in form data:

    selectedCourses[]=1050&selectedCourses[]=2000
    
  • 針對前列所有範例格式,模型繫結會將有兩個項目的陣列傳遞至 selectedCourses 參數:For all of the preceding example formats, model binding passes an array of two items to the selectedCourses parameter:

    • selectedCourses[0]=1050selectedCourses[0]=1050
    • selectedCourses[1]=2000selectedCourses[1]=2000

    使用下標數字 (... [0] ... [1] ...) 的資料格式,必須確定從零開始依序編號。Data formats that use subscript numbers (... [0] ... [1] ...) must ensure that they are numbered sequentially starting at zero. 下標編號中如有任何間距,則會忽略間隔後的所有項目。If there are any gaps in subscript numbering, all items after the gap are ignored. 例如,如果下標是 0 和 2,而不是 0 和 1,則忽略第二個項目。For example, if the subscripts are 0 and 2 instead of 0 and 1, the second item is ignored.

字典Dictionaries

針對 Dictionary 目標,模型繫結會尋找符合 parameter_nameproperty_name 的項目。For Dictionary targets, model binding looks for matches to parameter_name or property_name. 如果找不到相符項目,它會尋找其中一種沒有前置詞的受支援格式。If no match is found, it looks for one of the supported formats without the prefix. 例如:For example:

  • 假設目標參數是名為 selectedCoursesDictionary<int, string>Suppose the target parameter is a Dictionary<int, string> named selectedCourses:

    public IActionResult OnPost(int? id, Dictionary<int, string> selectedCourses)
    
  • 已張貼的表單或查詢字串資料看起來會像下列其中一個範例:The posted form or query string data can look like one of the following examples:

    selectedCourses[1050]=Chemistry&selectedCourses[2000]=Economics
    
    [1050]=Chemistry&selectedCourses[2000]=Economics
    
    selectedCourses[0].Key=1050&selectedCourses[0].Value=Chemistry&
    selectedCourses[1].Key=2000&selectedCourses[1].Value=Economics
    
    [0].Key=1050&[0].Value=Chemistry&[1].Key=2000&[1].Value=Economics
    
  • 針對前列所有範例格式,模型繫結會將有兩個項目的字典傳遞至 selectedCourses 參數:For all of the preceding example formats, model binding passes a dictionary of two items to the selectedCourses parameter:

    • selectedCourses["1050"]="Chemistry"selectedCourses["1050"]="Chemistry"
    • selectedCourses["2000"]="Economics"selectedCourses["2000"]="Economics"

特殊資料類型Special data types

模型繫結可以處理某些特殊資料類型。There are some special data types that model binding can handle.

IFormFile 和 IFormFileCollectionIFormFile and IFormFileCollection

HTTP 要求包含上傳的檔案。An uploaded file included in the HTTP request. 也支援多個檔案的 IEnumerable<IFormFile>Also supported is IEnumerable<IFormFile> for multiple files.

CancellationTokenCancellationToken

用來取消非同步控制器中的活動。Used to cancel activity in asynchronous controllers.

FormCollectionFormCollection

用來擷取已張貼表單資料中的所有值。Used to retrieve all the values from posted form data.

輸入格式器Input formatters

要求本文中的資料可以是 JSON、XML 或某些其他格式。Data in the request body can be in JSON, XML, or some other format. 模型繫結會使用設定處理特定內容類型的「輸入格式器」 ,來剖析此資料。To parse this data, model binding uses an input formatter that is configured to handle a particular content type. 根據預設,ASP.NET Core 包含 JSON 型輸入格式器以處理 JSON 資料。By default, ASP.NET Core includes JSON based input formatters for handling JSON data. 您可以新增其他內容類型的其他格式器。You can add other formatters for other content types.

ASP.NET Core 選取以 Consumes 屬性為基礎的輸入格式器。ASP.NET Core selects input formatters based on the Consumes attribute. 若無任何屬性,則它會使用 Content-Type 標頭If no attribute is present, it uses the Content-Type header.

使用內建的 XML 輸入格式器:To use the built-in XML input formatters:

  • 安裝 Microsoft.AspNetCore.Mvc.Formatters.Xml NuGet 套件。Install the Microsoft.AspNetCore.Mvc.Formatters.Xml NuGet package.

  • Startup.ConfigureServices 中,呼叫 AddXmlSerializerFormattersAddXmlDataContractSerializerFormattersIn Startup.ConfigureServices, call AddXmlSerializerFormatters or AddXmlDataContractSerializerFormatters.

    services.AddMvc(options =>
    {
        options.ValueProviderFactories.Add(new CookieValueProviderFactory());
        options.ModelMetadataDetailsProviders.Add(
            new ExcludeBindingMetadataProvider(typeof(System.Version)));
        options.ModelMetadataDetailsProviders.Add(
            new SuppressChildValidationMetadataProvider(typeof(System.Guid)));
    })
    .AddXmlSerializerFormatters()
    .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    
  • Consumes 屬性套用至要求本文應為 XML 的控制器類別或動作方法。Apply the Consumes attribute to controller classes or action methods that should expect XML in the request body.

    [HttpPost]
    [Consumes("application/xml")]
    public ActionResult<Pet> Create(Pet pet)
    

    如需詳細資訊,請參閱 XML 序列化簡介For more information, see Introducing XML Serialization.

排除模型繫結中的指定類型Exclude specified types from model binding

模型繫結和驗證系統的行為是由 ModelMetadata 所驅動。The model binding and validation systems' behavior is driven by ModelMetadata. 您可以將詳細資料提供者新增至 MvcOptions.ModelMetadataDetailsProviders,藉以自訂 ModelMetadataYou can customize ModelMetadata by adding a details provider to MvcOptions.ModelMetadataDetailsProviders. 內建的詳細資料提供者可用於停用模型繫結或驗證所指定類型。Built-in details providers are available for disabling model binding or validation for specified types.

若要停用指定類型之所有模型的模型繫結,請在 Startup.ConfigureServices 中新增 ExcludeBindingMetadataProviderTo disable model binding on all models of a specified type, add an ExcludeBindingMetadataProvider in Startup.ConfigureServices. 例如,若要對類型為 System.Version 的所有模型停用模型繫結:For example, to disable model binding on all models of type System.Version:

services.AddMvc(options =>
{
    options.ValueProviderFactories.Add(new CookieValueProviderFactory());
    options.ModelMetadataDetailsProviders.Add(
        new ExcludeBindingMetadataProvider(typeof(System.Version)));
    options.ModelMetadataDetailsProviders.Add(
        new SuppressChildValidationMetadataProvider(typeof(System.Guid)));
})
.AddXmlSerializerFormatters()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

若要停用指定類型屬性的驗證,請在 Startup.ConfigureServices 中新增 SuppressChildValidationMetadataProviderTo disable validation on properties of a specified type, add a SuppressChildValidationMetadataProvider in Startup.ConfigureServices. 例如,若要針對類型為 System.Guid 的屬性停用驗證:For example, to disable validation on properties of type System.Guid:

services.AddMvc(options =>
{
    options.ValueProviderFactories.Add(new CookieValueProviderFactory());
    options.ModelMetadataDetailsProviders.Add(
        new ExcludeBindingMetadataProvider(typeof(System.Version)));
    options.ModelMetadataDetailsProviders.Add(
        new SuppressChildValidationMetadataProvider(typeof(System.Guid)));
})
.AddXmlSerializerFormatters()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

自訂模型繫結器Custom model binders

您可以撰寫自訂的模型繫結器來擴充模型繫結,並使用 [ModelBinder] 屬性以針對特定目標來選取它。You can extend model binding by writing a custom model binder and using the [ModelBinder] attribute to select it for a given target. 深入了解自訂模型繫結Learn more about custom model binding.

手動模型繫結Manual model binding

使用 TryUpdateModelAsync 方法即可手動叫用模型繫結。Model binding can be invoked manually by using the TryUpdateModelAsync method. 此方法已於 ControllerBasePageModel 類別中定義。The method is defined on both ControllerBase and PageModel classes. 方法多載可讓您指定要使用的前置詞和值提供者。Method overloads let you specify the prefix and value provider to use. 如果模型繫結失敗,此方法會傳回 falseThe method returns false if model binding fails. 以下為範例:Here's an example:

if (await TryUpdateModelAsync<InstructorWithCollection>(
    newInstructor,
    "Instructor",
    i => i.FirstMidName, i => i.LastName, i => i.HireDate))
{
    _instructorsInMemoryStore.Add(newInstructor);
    return RedirectToPage("./Index");
}
PopulateAssignedCourseData(newInstructor);
return Page();

[FromServices] 屬性[FromServices] attribute

這個屬性名稱會遵循指定資料來源的模型繫結屬性模式。This attribute's name follows the pattern of model binding attributes that specify a data source. 但它與來自值提供者的資料繫結無關。But it's not about binding data from a value provider. 它從相依性插入容器取得類型的執行個體。It gets an instance of a type from the dependency injection container. 其目的是只有在呼叫特定方法時,才在您需要服務時提供建構函式插入的替代項目。Its purpose is to provide an alternative to constructor injection for when you need a service only if a particular method is called.

其他資源Additional resources