備註
這會利用 System.Web 配接器 來簡化移轉。
在 ASP.NET Framework 應用程式中,設定 <machineKey> 和 System.Web 介面程式,使兩個應用程式能夠共享相容的資料保護配置。 如需有關替換 <machineKey>的完整背景資訊,請參見 ASP.NET Core 中替換 ASP.NET 的 machineKey。
本指南建立在 System.Web 介面卡主機模型之上,使資料保護服務在主機依賴注入(DI)容器中註冊,並於整個 ASP.NET Framework 應用程式中提供。 透過整合由適配器提供的主機 DI,現有 ASP.NET Framework 元件可以解析 IDataProtectionProvider、IDataProtector及相關類型。
ASP.NET Framework 應用程式與 ASP.NET Core 應用程式都必須使用共用的應用程式名稱與金鑰儲存庫來保護資料,以確保受保護的有效載荷能在應用程式間往返。
- 在兩個應用程式中,使用相同的邏輯應用程式名稱呼叫
SetApplicationName(例如,"my-app")。 - 設定
PersistKeysToFileSystem指向兩個應用程式都能讀寫的同一個金鑰儲存庫位置。
備註
所使用的 PersistKeysToFileSystem 目錄是共享資料保護金鑰的後備儲存庫。 在生產環境中,使用耐用的共享儲存(例如 UNC 共享、Redis 或 Azure Blob 儲存),並且依照 Configure ASP.NET Core Data Protection 和 ASP.NET Core Data Protection Overview 中的金鑰管理指南進行操作。
設定 ASP.NET Framework 應用程式
若要在 ASP.NET Framework 應用程式中實作此設定,請確保該 Microsoft.AspNetCore.SystemWebAdapters.FrameworkServices 套件已安裝在 ASP.NET Framework 應用程式中。
當你在 ASP.NET Framework 應用程式安裝套件 Microsoft.AspNetCore.SystemWebAdapters.FrameworkServices 時,通常會自動設定 <machineKey> 。 如果 <machineKey> 不存在,或你需要檢查設定,請在 Web.config 中將配置器設定為使用相容性資料保護器,如下所示:
<configuration>
<system.web>
<httpRuntime targetFramework="4.8.1" />
<machineKey
compatibilityMode="Framework45"
dataProtectorType="Microsoft.AspNetCore.DataProtection.SystemWeb.CompatibilityDataProtector,
Microsoft.AspNetCore.DataProtection.SystemWeb" />
</system.web>
</configuration>
接著,在 Global.asax.cs中註冊 System.Web 介面卡的主機,並設定資料保護,使用與 ASP.NET Core 應用程式相同的應用程式名稱與金鑰儲存庫。 以下範例改編自 MachineKey Framework 範例:
using System.IO;
using System.Web;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.SystemWebAdapters.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace DataProtectionDemo
{
public class MvcApplication : HttpApplication
{
protected void Application_Start()
{
HttpApplicationHost.RegisterHost(builder =>
{
builder.AddServiceDefaults();
builder.AddDataProtection()
.SetApplicationName("my-app")
.PersistKeysToFileSystem(new DirectoryInfo(@"\\server\share\myapp-keys\"));
});
}
}
}
此配置:
- 設定一個共用的應用程式名稱(
my-app),ASP.NET Core 應用程式也必須使用。 - 配置一個共享金鑰庫(例如,UNC 共享),讓兩個應用程式都能存取。
- 確保
<machineKey>操作(表單認證、視圖狀態及MachineKey.Protect相關 API)經過 ASP.NET 核心資料保護。 - 作為 ASP.NET Framework 主機的一部分運行,使現有
<machineKey>基於功能的功能使用與 ASP.NET Core 相同的資料保護系統。
設定 ASP.NET Core 應用程式
ASP.NET Core 應用程式中無需額外設定資料保護。 只要設定和 ASP.NET Framework 應用程式使用的應用程式名稱和金鑰儲存位置一樣即可。
using Microsoft.AspNetCore.DataProtection;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDataProtection()
.SetApplicationName(MachineKeyExampleHandler.AppName)
.PersistKeysToFileSystem(
new DirectoryInfo(Path.Combine(Path.GetTempPath(), "sharedkeys", MachineKeyExampleHandler.AppName)));
var app = builder.Build();
// Configure application
app.Run();