ASP.NET Core MVC 的相容性版本

作者:Rick Anderson

SetCompatibilityVersion 方法對於 ASP.NET Core 3.0 應用程式來說是一個無作業的方法。 也就是說,使用任何 CompatibilityVersion 值呼叫 SetCompatibilityVersion 對該應用程式都沒有影響。

若要了解 SetCompatibilityVersion 如何與 ASP.NET Core 2.x 應用程式一起運作,請選取本文的 ASP.NET Core 2.2 版本

SetCompatibilityVersion 方法可讓 ASP.NET Core 2.x 應用程式加入或退出 ASP.NET Core MVC 2.1 或 2.2 中所引入的可能重大行為變更。 這些可能的重大行為變更通常在於 MVC 子系統的運作方式,以及執行階段呼叫您的程式碼的方式。 透過選擇加入,您可以取得最新的行為和 ASP.NET Core 的長期行為。

下列程式碼會將相容性模式設定為 ASP.NET Core 2.2:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc()
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

建議您使用最新版本 (CompatibilityVersion.Latest) 測試應用程式。 預計大部分的應用程式都不會使用最新版本進行重大行為變更。

呼叫 SetCompatibilityVersion(CompatibilityVersion.Version_2_0) 的應用程式會受到保護,以防止 ASP.NET Core 2.1/2.2 MVC 版本中所引進的可能重大行為變更。 這項保護:

  • 不適用於所有 2.1 和更新版本的變更,它的目標是 MVC 子系統中的可能重大 ASP.NET Core 執行階段行為變更。
  • 不會延伸至 ASP.NET Core 3.0。

適用於 ASP.NET Core 2.1 和 2.2 應用程式且不會呼叫 SetCompatibilityVersion 的預設相容性為 2.0 相容性。 也就是說,不呼叫 SetCompatibilityVersion 等同於呼叫 SetCompatibilityVersion(CompatibilityVersion.Version_2_0)

下列程式碼會將相容性模式設定為 ASP.NET Core 2.2,但下列行為除外:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc()
        // Include the 2.2 behaviors
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
        // Except for the following.
        .AddMvcOptions(options =>
        {
            // Don't combine authorize filters (keep 2.0 behavior).
            options.AllowCombiningAuthorizeFilters = false;
            // All exceptions thrown by an IInputFormatter are treated
            // as model state errors (keep 2.0 behavior).
            options.InputFormatterExceptionPolicy =
                InputFormatterExceptionPolicy.AllExceptions;
        });
}

對於出現重大行為變更的應用程式,使用適當的相容性參數:

  • 可讓您使用最新版本,並選擇退出特定的重大行為變更。
  • 讓您有時間來更新您的應用程式,使其適用於最新的變更。

MvcOptions 文件充分說明變更的項目,以及所做變更對於大部分使用者來說都得到改善的原因。

對於 ASP.NET Core 3.0,相容性參數支援的舊行為已被移除。 我們覺得這些是有利於幾乎所有使用者的正向變更。 透過在 2.1 和 2.2 中引入這些變更,大部分的應用程式都可以受益,而其他應用程式則有時間進行更新。