環境會提供應用程式運行的背景。 參數表示在執行應用程式時要求外部值的能力。 參數可用來在本機執行時提供值給應用程式,或在部署時提示值。 它們可用來建立各種案例的模型,包括秘密、連接字串和其他可能因環境而異的組態值。
參數值
參數值會從 Parameters AppHost組態的區段讀取,並用來在本機執行時提供值給應用程式。 當您執行或發佈應用程式時,如果未設定值,系統會提示您提供它。
請考慮下列範例 AppHost AppHost.cs 檔案:
var builder = DistributedApplication.CreateBuilder(args);
// Add a parameter named "example-parameter-name"
var parameter = builder.AddParameter("example-parameter-name");
builder.AddProject<Projects.ApiService>("api")
.WithEnvironment("ENVIRONMENT_VARIABLE_NAME", parameter);
上述程式碼新增名為 AppHost 的參數 example-parameter-name 。 然後,參數會以名為 Projects.ApiService的環境變數的形式傳遞至 ENVIRONMENT_VARIABLE_NAME 專案。
設定參數值
將參數新增至產生器只是組態的一個層面。 您也必須提供 參數的值。 該值可以在 AppHost 組態檔中提供、設定為使用者密碼,或在 任何其他標準組態中進行設定。 當找不到參數值時,系統會在您執行或發佈應用程式時提示您輸入參數值。
請考慮下列 AppHost 組態檔 appsettings.json:
{
"Parameters": {
"example-parameter-name": "local-value"
}
}
先前的 JSON 是在 AppHost 組態的 Parameters 節中設定的參數。 換句話說,該 AppHost 能夠在配置時找到參數。 例如,您可以走到 IDistributedApplicationBuilder.Configuration 並使用 Parameters:example-parameter-name 鍵來訪問值:
var builder = DistributedApplication.CreateBuilder(args);
var key = $"Parameters:example-parameter-name";
var value = builder.Configuration[key]; // value = "local-value"
Important
不過,您不需要在AppHost中自行存取此組態值。 相反地,ParameterResource 會用來將參數值傳遞至相依資源。 最常做為環境變數。
在儀錶板中請求輸入參數值
如果您的程式碼新增了參數,但未設定參數,您會在儀表板中 Aspire 看到設定其值的提示。 [未解決的參數] 訊息隨即出現,您可以選取 Enter 值來解決問題:
當您選取 [ 輸入值] 時, Aspire 會顯示可用來設定每個遺漏參數值的表單。
您也可以使用下列方法來控制儀錶板顯示這些參數的方式:
-
WithDescription:使用此方法提供文字描述,可協助使用者了解 參數的目的。 若要在 Markdown 中提供格式化的描述,請使用參數enableMarkdown: true。 -
WithCustomInput:使用此方法提供可自定義參數對話框的回呼方法。 例如,在此回呼中,您可以自定義預設值、輸入類型、標籤和佔位元文字。
此程式代碼示範如何設定描述並使用回呼:
#pragma warning disable ASPIREINTERACTION001 // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed.
var externalServiceUrl = builder.AddParameter("external-service-url")
.WithDescription("The URL of the external service.")
.WithCustomInput(p => new()
{
InputType = InputType.Text,
Value = "https://example.com",
Name = p.Name,
Placeholder = $"Enter value for {p.Name}",
Description = p.Description
});
var externalService = builder.AddExternalService("external-service", externalServiceUrl);
#pragma warning restore ASPIREINTERACTION001
程序代碼會在儀錶板中轉譯此控件:
Note
儀錶板參數對話框包含 [ 儲存至用戶密碼 ] 複選框。 選取此選項可將敏感性值儲存在AppHost的用戶密碼中,以取得額外的保護。 如需秘密參數值的詳細資訊,請參閱 秘密值。
清單中的參數表示法
Aspire 使用 部署資訊清單 來代表應用程式的資源及其關聯性。 參數會在清單檔中表示為名為 parameter.v0的新原始類型:
{
"resources": {
"example-parameter-name": {
"type": "parameter.v0",
"value": "{value.inputs.value}",
"inputs": {
"value": {
"type": "string"
}
}
}
}
}
秘密值
參數可用來建立秘密模型。 當參數標示為秘密時,它會作為指令清單的提示,指出值應視為秘密。 當您發佈應用程式時,系統會提示您輸入值並儲存在安全的位置。 當您在本機執行應用程式時,會從 AppHost 組態的區段讀取 Parameters 值。
請考慮下列範例 AppHost AppHost.cs 檔案:
var builder = DistributedApplication.CreateBuilder(args);
// Add a secret parameter named "secret"
var secret = builder.AddParameter("secret", secret: true);
builder.AddProject<Projects.ApiService>("api")
.WithEnvironment("SECRET", secret);
builder.Build().Run();
現在考慮以下AppHost配置文件 appsettings.json:
{
"Parameters": {
"secret": "local-secret"
}
}
清單顯示如下:
{
"resources": {
"value": {
"type": "parameter.v0",
"value": "{value.inputs.value}",
"inputs": {
"value": {
"type": "string",
"secret": true
}
}
}
}
}
連接字串值
參數可用來建立連接字串的模型。 當您發佈應用程式時,系統會提示您輸入值並儲存在安全的位置。 當您在本機執行應用程式時,會從 AppHost 組態的區段讀取 ConnectionStrings 值。
Note
連接字串可用來代表各種連線資訊,包括資料庫連接、訊息代理程式、端點 URI 和其他服務。 在命名法中 Aspire ,術語「連接字串」用於表示任何類型的連線資訊。
請考慮下列範例 AppHost AppHost.cs 檔案:
var builder = DistributedApplication.CreateBuilder(args);
var redis = builder.AddConnectionString("redis");
builder.AddProject<Projects.WebApplication>("api")
.WithReference(redis)
.WaitFor(redis);
builder.Build().Run();
Note
使用 WaitFor 搭配連接字串時,會隱含等待該連接字串所連接的資源。
現在考慮以下AppHost配置文件 appsettings.json:
{
"ConnectionStrings": {
"redis": "local-connection-string"
}
}
如需有關連接字串及其在部署指令清單中表示的詳細資訊,請參閱 連接字串和系結參考。
使用參考表達式建置連接字串
如果您要從參數建構連接字串,並確保它在開發和生產環境中得到正確處理,請使用 AddConnectionString 搭配 ReferenceExpression。
例如,如果您有一個秘密參數來儲存連接字串的一小部分,請使用此程式代碼來插入它:
var secretKey = builder.AddParameter("secretkey", secret: true);
var connectionString = builder.AddConnectionString(
"composedconnectionstring",
ReferenceExpression.Create($"Endpoint=https://api.contoso.com/v1;Key={secretKey}"));
builder.AddProject<Projects.AspireReferenceExpressions_CatalogAPI>("catalogapi")
.WithReference(connectionString)
.WaitFor(connectionString);
您也可以使用參考運算式,將文字附加到由 Aspire 資源建立的連線字串中。 例如,當您將資源新增 PostgreSQL 至 Aspire 解決方案時,資料庫伺服器會在容器中執行,併為其制定連接字串。 在下列程式代碼中,額外的屬性 Include Error Details 會在傳遞至取用專案之前附加至該連接字串:
var postgres = builder.AddPostgres("postgres");
var database = postgres.AddDatabase("db");
var pgConnectionString = builder.AddConnectionString(
"pgdatabase",
ReferenceExpression.Create($"{database};Include Error Details=true"));
builder.AddProject<Projects.AspireReferenceExpressions_CustomerAPI>("customerapi")
.WithReference(pgConnectionString)
.WaitFor(pgConnectionString);
參數範例
若要表示參數,請考慮下列範例程式代碼:
var builder = DistributedApplication.CreateBuilder(args);
var db = builder.AddSqlServer("sql")
.PublishAsConnectionString()
.AddDatabase("db");
var insertionRows = builder.AddParameter("insertionRows");
builder.AddProject<Projects.Parameters_ApiService>("api")
.WithEnvironment("InsertionRows", insertionRows)
.WithReference(db);
builder.Build().Run();
執行以下步驟:
- 新增名為 SQL Server 的
sql資源,並將其發佈為連接字串。 - 新增名為
db的資料庫。 - 新增名為
insertionRows的參數。 - 新增名為
api的專案,並將它與Projects.Parameters_ApiService專案資源類型參數產生關聯。 - 將
insertionRows參數傳遞至api專案。 - 參考
db資料庫。
在AppHost配置檔案insertionRows的區段中讀取Parameters參數的值appsettings.json。
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
"Aspire.Hosting.Dcp": "Warning"
}
},
"Parameters": {
"insertionRows": "1"
}
}
Parameters_ApiService 項目會取用 insertionRows 參數。 請考慮範例檔案 Program.cs:
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
int insertionRows = builder.Configuration.GetValue<int>("InsertionRows", 1);
builder.AddServiceDefaults();
builder.AddSqlServerDbContext<MyDbContext>("db");
var app = builder.Build();
app.MapGet("/", async (MyDbContext context) =>
{
// You wouldn't normally do this on every call,
// but doing it here just to make this simple.
context.Database.EnsureCreated();
for (var i = 0; i < insertionRows; i++)
{
var entry = new Entry();
await context.Entries.AddAsync(entry);
}
await context.SaveChangesAsync();
var entries = await context.Entries.ToListAsync();
return new
{
totalEntries = entries.Count,
entries
};
});
app.Run();
另請參閱
- Aspire 部署工具產生器的資訊清單格式
- ASP.NET Core 將 SQL Server 應用程式連線到 Aspire