共用方式為


ASP.NET Core MVC 的相容性版本

作者:Rick Anderson

方法 SetCompatibilityVersion 是 ASP.NET Core 3.0 應用程式的 no-op。 也就是說,使用任何SetCompatibilityVersion的值來呼叫CompatibilityVersion不會影響應用程式。

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。

呼叫SetCompatibilityVersion之 ASP.NET Core 2.1 和 2.2 應用程式的預設相容性為 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 中引進這些變更,大部分的應用程式都可以受益,而其他人則有時間更新。