使用 Azure Functions 開發 C# 類別庫函式
重要
支援將於 2026 年 11 月 10 日結束進程模型。 強烈建議您將 應用程式移轉至隔離的背景工作模型 ,以取得完整支援。
本文是使用 .NET 類別庫中的 C# 開發 Azure Functions 的簡介。 這些類別庫可用來 搭配 Functions 執行時間執行同進程。 您的 .NET 函式也可以從 Functions 運行時間執行_isolated,這提供數個優點。 若要深入瞭解,請參閱 隔離的背景工作模型。 如需這兩個模型之間的全面比較,請參閱 同進程模型與隔離背景工作模型之間的差異。
重要
本文支援使用執行階段執行內含式的 .NET 類別庫函式。 您的 C# 函式也可以跨處理序執行,並與 Functions 執行階段隔離。 隔離式背景工作處理序模型是在目前版本的 Functions 執行階段中執行非 LTS 版本的 .NET 和 .NET Framework 應用程式的唯一方式。 若要深入了解,請參閱 .NET 隔離式背景工作處理序函式。 如需隔離背景工作進程與同進程 .NET Functions 之間的全面比較,請參閱 同進程與隔離背景工作進程 .NET Azure Functions 之間的差異。
身為 C# 開發人員,您可能也對下列其中一篇文章感興趣:
開始使用 | 概念 | 引導式學習/範例 |
---|---|---|
Azure Functions 支援 C# 和 C# 腳本程式設計語言。 如果您想要在 Azure 入口網站 中使用 C# 的指引,請參閱 C# 腳稿 (.csx) 開發人員參考。
支援的版本
Functions 執行階段的版本支援 .NET 特定版本。 若要深入瞭解 Functions 版本,請參閱 Azure Functions 執行階段版本概觀。 版本支援也取決於函式執行內含式或隔離式背景工作處理序。
注意
若要瞭解如何變更函數應用程式所使用的 Functions 執行階段版本,請參閱檢視及更新目前的執行階段版本。
下表顯示可與 Functions 特定版本搭配使用的最高層級 .NET 或 .NET Framework。
Functions 執行階段版本 | 隔離式背景工作角色模型 | 進程內模型5 |
---|---|---|
Functions 4.x | .NET 8.0 .NET 7.01 .NET 6.02 .NET Framework 4.83 |
.NET 6.02 |
Functions 1.x4 | n/a | .NET Framework 4.8 |
1 .NET 7 於 2024 年 5 月 14 日結束正式支援。
2 .NET 6 於 2024 年 11 月 12 日結束正式支援。
3 建置程式也需要 .NET SDK。
4 1.x 版的 Azure Functions 執行階段於 2026 年 9 月 14 日結束支援。 如需詳細資訊,請參閱此支援公告。 如需持續的完整支援,您應該將應用程式移轉至 4.x 版。
5 支援會在 2026 年 11 月 10 日結束進程模型。 如需詳細資訊,請參閱此支援公告。 如需持續的完整支援,您應該 將應用程式遷移至隔離的背景工作模型。
如需有關 Azure Functions 版本的最新新聞,包括移除特定舊版次要版本,請持續關注 Azure App Service 公告。
Functions 類別庫專案
在 Visual Studio 中 ,Azure Functions 專案範本會建立包含下列檔案的 C# 類別庫專案:
- host.json - 會在本機或 Azure 中執行時,儲存會影響專案中所有函式的組態設定。
- local.settings.json - 儲存在本機執行時所使用的應用程式設定和 連接字串。 此檔案包含秘密,且不會發佈至 Azure 中的函式應用程式。 相反地, 將應用程式設定新增至函式應用程式。
當您建置專案時,組建輸出目錄中會產生類似下列範例的資料夾結構:
<framework.version>
| - bin
| - MyFirstFunction
| | - function.json
| - MySecondFunction
| | - function.json
| - host.json
此目錄是部署至 Azure 中函式應用程式的內容。 Functions 運行時間 2.x 版所需的系結延伸模組會新增至專案作為 NuGet 套件。
重要
建置程式會 為每個函式 建立function.json檔案。 此 function.json 檔案並非要直接編輯。 您無法編輯此檔案來變更系結組態或停用函式。 若要瞭解如何停用函式,請參閱 如何停用函式。
辨識為函式的方法
在類別庫中,函式是具有 FunctionName
和 觸發程式屬性的方法,如下列範例所示:
public static class SimpleExample
{
[FunctionName("QueueTrigger")]
public static void Run(
[QueueTrigger("myqueue-items")] string myQueueItem,
ILogger log)
{
log.LogInformation($"C# function processed: {myQueueItem}");
}
}
屬性會將 FunctionName
方法標示為函式進入點。 名稱在專案內必須是唯一的,開頭為字母,且只包含字母、數位、 _
和 -
,長度最多 127 個字元。 項目範本通常會建立名為 Run
的方法,但方法名稱可以是任何有效的 C# 方法名稱。 上述範例顯示正在使用的靜態方法,但不需要函式是靜態的。
觸發程式屬性會指定觸發程式類型,並將輸入數據系結至方法參數。 範例函式是由佇列訊息所觸發,佇列訊息會傳遞至 參數中的 myQueueItem
方法。
方法簽章參數
方法簽章可能包含與觸發程式屬性搭配使用的參數以外的參數。 以下是您可以包含的其他一些參數:
- 輸入與輸出系結會 以屬性裝飾,以標示為這類系結。
- 或 (僅限 1.x 版) 參數進行記錄。
TraceWriter
ILogger
- 正常
CancellationToken
關機的參數。 - 系結表達式 參數以取得觸發程式元數據。
函式簽章中的參數順序並不重要。 例如,您可以在其他系結之前或之後放置觸發程序參數,並在觸發程式或系結參數之前或之後放置記錄器參數。
輸出繫結
函式可以使用輸出參數來定義零或多個輸出系結。
下列範例會藉由新增名為 的 myQueueItemCopy
輸出佇列系結來修改上述的系結。 函式會寫入訊息的內容,以將函式觸發至不同佇列中的新訊息。
public static class SimpleExampleWithOutput
{
[FunctionName("CopyQueueMessage")]
public static void Run(
[QueueTrigger("myqueue-items-source")] string myQueueItem,
[Queue("myqueue-items-destination")] out string myQueueItemCopy,
ILogger log)
{
log.LogInformation($"CopyQueueMessage function processed: {myQueueItem}");
myQueueItemCopy = myQueueItem;
}
}
指派給輸出系結的值會在函式結束時寫入。 只要將值指派給多個輸出參數,即可在函式中使用多個輸出系結。
系結參考文章(例如 儲存體 佇列)說明您可以搭配觸發程式、輸入或輸出系結屬性使用的參數類型。
系結表達式範例
下列程式代碼會從應用程式設定取得要監視的佇列名稱,並在 參數中 insertionTime
取得佇列訊息建立時間。
public static class BindingExpressionsExample
{
[FunctionName("LogQueueMessage")]
public static void Run(
[QueueTrigger("%queueappsetting%")] string myQueueItem,
DateTimeOffset insertionTime,
ILogger log)
{
log.LogInformation($"Message content: {myQueueItem}");
log.LogInformation($"Created at: {insertionTime}");
}
}
自動產生的function.json
建置程式會在建置資料夾中的函式資料夾中建立 function.json 檔案。 如先前所述,此檔案並非要直接編輯。 您無法編輯此檔案來變更系結組態或停用函式。
此檔案的目的是將資訊提供給調整控制器,以用於 調整使用量方案的決策。 基於這個理由,檔案只有觸發程序資訊,而不是輸入/輸出系結。
產生的function.json檔案包含configurationSource
屬性,指示運行時間使用 .NET 屬性進行系結,而不是function.json組態。 以下是範例:
{
"generatedBy": "Microsoft.NET.Sdk.Functions-1.0.0.0",
"configurationSource": "attributes",
"bindings": [
{
"type": "queueTrigger",
"queueName": "%input-queue-name%",
"name": "myQueueItem"
}
],
"disabled": false,
"scriptFile": "..\\bin\\FunctionApp1.dll",
"entryPoint": "FunctionApp1.QueueTrigger.Run"
}
Microsoft.NET.Sdk.Functions
function.json檔案產生是由 NuGet 套件 Microsoft.NET.Sdk.Functions 執行。
下列範例顯示具有相同套件之不同目標架構之Sdk
檔案的相關部分.csproj
:
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<AzureFunctionsVersion>v4</AzureFunctionsVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="4.1.1" />
</ItemGroup>
套件相 Sdk
依性包括觸發程式和系結。 1.x 專案是指 1.x 觸發程式和系結,因為這些觸發程式和系結是以 .NET Framework 為目標,而 4.x 觸發程式和系結則以 .NET Core 為目標。
套件Sdk
也相依於 Newtonsoft.Json,並間接依賴 WindowsAzure.儲存體。 這些相依性可確保您的專案使用與項目目標 Functions 執行時間版本搭配使用的套件版本。 例如, Newtonsoft.Json
具有 .NET Framework 4.6.1 版 11,但以 .NET Framework 4.6.1 為目標的 Functions 運行時間只與 Newtonsoft.Json
9.0.1 相容。 因此,該專案中的函式程式代碼也必須使用 Newtonsoft.Json
9.0.1。
的原始程式碼 Microsoft.NET.Sdk.Functions
可在 GitHub 存放庫 azure-functions-vs-build-sdk 中使用。
本機運行時間版本
Visual Studio 會 使用 Azure Functions Core Tools 在本機電腦上執行 Functions 專案。 Core Tools 是 Functions 運行時間的命令行介面。
如果您使用 Windows 安裝程式 (MSI) 套件或使用 npm 安裝 Core Tools,則不會影響 Visual Studio 所使用的 Core Tools 版本。 針對 Functions 執行時間 1.x 版,Visual Studio 會將 Core Tools 版本儲存在 %USERPROFILE%\AppData\Local\Azure.Functions.Cli 中,並使用儲存在那裡的最新版本。 針對 Functions 4.x,Core Tools 會包含在 Azure Functions 和 Web Jobs Tools 擴充功能中。 針對 Functions 1.x,您可以在執行 Functions 專案時,查看主控台輸出中所使用的版本:
[3/1/2018 9:59:53 AM] Starting Host (HostId=contoso2-1518597420, Version=2.0.11353.0, ProcessId=22020, Debug=False, Attempt=0, FunctionsExtensionVersion=)
ReadyToRun
您可以將函式應用程式編譯為 ReadyToRun 二進位檔。 ReadyToRun 是一種預先編譯的形式,可改善啟動效能,以協助降低在取用方案中執行時冷啟動的影響。
ReadyToRun 適用於 .NET 6 和更新版本,且需要 Azure Functions 運行時間 4.0 版。
若要將專案編譯為 ReadyToRun,請藉由新增 <PublishReadyToRun>
和 <RuntimeIdentifier>
元素來更新項目檔。 以下是發佈至 Windows 32 位函式應用程式的組態。
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<AzureFunctionsVersion>v4</AzureFunctionsVersion>
<PublishReadyToRun>true</PublishReadyToRun>
<RuntimeIdentifier>win-x86</RuntimeIdentifier>
</PropertyGroup>
重要
從 .NET 6 開始,已新增複合 ReadyToRun 編譯的支援。 請參閱 ReadyToRun 跨平台和架構限制。
您也可以從命令行使用 ReadyToRun 建置應用程式。 如需詳細資訊,請參閱 -p:PublishReadyToRun=true
中的 dotnet publish
選項。
支援的繫結類型
每個系結都有自己的支援類型;例如,Blob 觸發程式屬性可以套用至字串參數、POCO 參數、參數,或數個其他支援類型的任一 CloudBlockBlob
類型。 Blob 系結的系結參考文章會列出所有支持的參數類型。 如需詳細資訊,請參閱觸發程序和繫結以及每個繫結類型的繫結參考文件。
提示
如果您打算使用 HTTP 或 WebHook 的繫結,請做好規劃,以免因為 HttpClient
具現化不當而耗盡連接埠。 如需詳細資訊,請參閱如何管理 Azure Functions 中的連線。
繫結至方法傳回值
您可以將 屬性套用至方法傳回值,以使用輸出系結的方法傳回值。 如需範例,請參閱 觸發程式和系結。
唯有成功的函式執行一律導致傳回值傳遞至輸出繫結時,才使用此傳回值。 否則,使用 ICollector
或 IAsyncCollector
,如下一節所示。
撰寫多個輸出值
若要將多個值寫入至輸出繫結,或者如果成功的函式叫用可能未導致將任何項目傳遞至輸出繫結,請使用 ICollector
或 IAsyncCollector
類型。 這些類型是在方法完成時,寫入至輸出繫結的唯寫集合。
這個範例會使用 ICollector
將多個佇列訊息寫入相同佇列:
public static class ICollectorExample
{
[FunctionName("CopyQueueMessageICollector")]
public static void Run(
[QueueTrigger("myqueue-items-source-3")] string myQueueItem,
[Queue("myqueue-items-destination")] ICollector<string> myDestinationQueue,
ILogger log)
{
log.LogInformation($"C# function processed: {myQueueItem}");
myDestinationQueue.Add($"Copy 1: {myQueueItem}");
myDestinationQueue.Add($"Copy 2: {myQueueItem}");
}
}
Async
若要讓函式變成非同步,請使用 async
關鍵字並傳回 Task
物件。
public static class AsyncExample
{
[FunctionName("BlobCopy")]
public static async Task RunAsync(
[BlobTrigger("sample-images/{blobName}")] Stream blobInput,
[Blob("sample-images-copies/{blobName}", FileAccess.Write)] Stream blobOutput,
CancellationToken token,
ILogger log)
{
log.LogInformation($"BlobCopy function processed.");
await blobInput.CopyToAsync(blobOutput, 4096, token);
}
}
您無法在非同步函式中使用 out
參數。 針對輸出繫結,請改為使用函式傳回值或收集器物件。
取消權杖
可以接受 CancellationToken 參數的函式,讓作業系統能夠在函式即將終止時通知您的程式碼。 您可以使用此通知來確保函數不會在讓資料維持不一致狀態的情況下意外終止。
當您有一個以批次處理訊息的函式時,請考慮此情況。 下列 Azure 服務匯流排 觸發函式會處理 ServiceBusReceivedMessage 物件的陣列,此陣列代表要由特定函式調用處理的傳入訊息批次:
using Azure.Messaging.ServiceBus;
using System.Threading;
namespace ServiceBusCancellationToken
{
public static class servicebus
{
[FunctionName("servicebus")]
public static void Run([ServiceBusTrigger("csharpguitar", Connection = "SB_CONN")]
ServiceBusReceivedMessage[] messages, CancellationToken cancellationToken, ILogger log)
{
try
{
foreach (var message in messages)
{
if (cancellationToken.IsCancellationRequested)
{
log.LogInformation("A cancellation token was received. Taking precautionary actions.");
//Take precautions like noting how far along you are with processing the batch
log.LogInformation("Precautionary activities --complete--.");
break;
}
else
{
//business logic as usual
log.LogInformation($"Message: {message} was processed.");
}
}
}
catch (Exception ex)
{
log.LogInformation($"Something unexpected happened: {ex.Message}");
}
}
}
}
記錄
在函式程式代碼中,您可以將輸出寫入 Application Insights 中顯示為追蹤的記錄。 寫入記錄的建議方式是包含 ILogger 型態的參數, 通常命名為 log
。 使用 TraceWriter
1.x 版的 Functions 運行時間,其也會寫入 Application Insights,但不支持結構化記錄。 請勿用來 Console.Write
寫入記錄,因為 Application Insights 不會擷取此數據。
ILogger
在您的函式定義中,包含支援結構化記錄的 ILogger 參數。
ILogger
使用物件時,您會在 ILogger 上呼叫Log<level>
擴充方法來建立記錄。 下列程式代碼會 Information
寫入類別 Function.<YOUR_FUNCTION_NAME>.User.
為 的記錄:
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, ILogger logger)
{
logger.LogInformation("Request for item with key={itemKey}.", id);
若要深入瞭解 Functions 如何實作 ILogger
,請參閱 收集遙測數據。 前面加上的 Function
類別假設您使用的是 ILogger
實例。 如果您選擇改用 ILogger<T>
,則類別名稱可能會改為以 為基礎 T
。
結構化記錄
占位元的順序,而不是其名稱,會決定記錄訊息中所使用的參數。 假設您有下列程式代碼:
string partitionKey = "partitionKey";
string rowKey = "rowKey";
logger.LogInformation("partitionKey={partitionKey}, rowKey={rowKey}", partitionKey, rowKey);
如果您保留相同的訊息字串,並反轉參數的順序,產生的消息正文就會有錯誤的位置值。
佔位元會以這種方式處理,讓您可以進行結構化記錄。 Application Insights 會儲存參數名稱/值組和訊息字串。 結果是訊息自變數會變成您可以查詢的欄位。
如果您的記錄器方法呼叫看起來像上一個範例,您可以查詢 欄位 customDimensions.prop__rowKey
。 已新增前置 prop__
詞,以確保運行時間新增的欄位與函式程式代碼所新增的欄位之間沒有衝突。
您也可以參考欄位 customDimensions.prop__{OriginalFormat}
來查詢原始訊息字串。
以下是數據的 JSON 表示 customDimensions
範例:
{
"customDimensions": {
"prop__{OriginalFormat}":"C# Queue trigger function processed: {message}",
"Category":"Function",
"LogLevel":"Information",
"prop__message":"c9519cbf-b1e6-4b9b-bf24-cb7d10b1bb89"
}
}
記錄自定義遙測
Application Insights SDK 有一個 Functions 特定版本,可用來將自定義遙測數據從函式傳送至 Application Insights: Microsoft.Azure.WebJobs.Logging.ApplicationInsights。 從命令提示字元使用下列命令來安裝此套件:
dotnet add package Microsoft.Azure.WebJobs.Logging.ApplicationInsights --version <VERSION>
在此命令中,將 取代<VERSION>
為支援已安裝 Microsoft.Azure.WebJobs 版本之此套件的版本。
下列 C# 範例使用 自定義遙測 API。 此範例適用於 .NET 類別庫,但 C# 腳本的 Application Insights 程式代碼相同。
2.x 版和更新版本的運行時間會使用Application Insights中的較新功能,自動將遙測與目前的作業相互關聯。 不需要手動設定作業 Id
、 ParentId
或 Name
欄位。
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.ApplicationInsights.Extensibility;
using System.Linq;
namespace functionapp0915
{
public class HttpTrigger2
{
private readonly TelemetryClient telemetryClient;
/// Using dependency injection will guarantee that you use the same configuration for telemetry collected automatically and manually.
public HttpTrigger2(TelemetryConfiguration telemetryConfiguration)
{
this.telemetryClient = new TelemetryClient(telemetryConfiguration);
}
[FunctionName("HttpTrigger2")]
public Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)]
HttpRequest req, ExecutionContext context, ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
DateTime start = DateTime.UtcNow;
// Parse query parameter
string name = req.Query
.FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0)
.Value;
// Write an event to the customEvents table.
var evt = new EventTelemetry("Function called");
evt.Context.User.Id = name;
this.telemetryClient.TrackEvent(evt);
// Generate a custom metric, in this case let's use ContentLength.
this.telemetryClient.GetMetric("contentLength").TrackValue(req.ContentLength);
// Log a custom dependency in the dependencies table.
var dependency = new DependencyTelemetry
{
Name = "GET api/planets/1/",
Target = "swapi.co",
Data = "https://swapi.co/api/planets/1/",
Timestamp = start,
Duration = DateTime.UtcNow - start,
Success = true
};
dependency.Context.User.Id = name;
this.telemetryClient.TrackDependency(dependency);
return Task.FromResult<IActionResult>(new OkResult());
}
}
}
在此範例中,自定義計量數據會先由主機匯總,再傳送至 customMetrics 數據表。 若要深入瞭解,請參閱 Application Insights 中的 GetMetric 檔。
在本機執行時,您必須使用Application Insights 金鑰將設定新增 APPINSIGHTS_INSTRUMENTATIONKEY
至 local.settings.json 檔案。
請勿呼叫 TrackRequest
或 StartOperation<RequestTelemetry>
,因為您會看到函式調用的重複要求。 Functions 運行時間會自動追蹤要求。
請勿設定 telemetryClient.Context.Operation.Id
。 當許多函式同時執行時,此全域設定會造成不正確的相互關聯。 相反地,請建立新的遙測實例 (DependencyTelemetry
, EventTelemetry
) 並修改其 Context
屬性。 然後將遙測實例傳入 (TrackDependency()
、 、 TrackMetric()
TrackEvent()
) 上的TelemetryClient
對應Track
方法。 此方法可確保遙測具有目前函式調用的正確相互關聯詳細數據。
測試函式
下列文章示範如何在本機執行內部 C# 類別庫函式,以進行測試:
環境變數
若要取得環境變數或應用程式設定值,請使用 System.Environment.GetEnvironmentVariable
,如下列程式碼範例所示:
public static class EnvironmentVariablesExample
{
[FunctionName("GetEnvironmentVariables")]
public static void Run([TimerTrigger("0 */5 * * * *")]TimerInfo myTimer, ILogger log)
{
log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
log.LogInformation(GetEnvironmentVariable("AzureWebJobsStorage"));
log.LogInformation(GetEnvironmentVariable("WEBSITE_SITE_NAME"));
}
private static string GetEnvironmentVariable(string name)
{
return name + ": " +
System.Environment.GetEnvironmentVariable(name, EnvironmentVariableTarget.Process);
}
}
在本機開發時,以及在 Azure 中執行時,都可以從環境變數讀取應用程式設定。 在本機開發時,應用程式設定來自 Values
local.settings.json 檔案中的集合。 在本機和 Azure 這兩個環境中, GetEnvironmentVariable("<app setting name>")
擷取具名應用程式設定的值。 例如,當您在本機執行時,如果您的 local.settings.json 檔案包含 { "Values": { "WEBSITE_SITE_NAME": "My Site Name" } }
,則會傳回「我的網站名稱」。
System.Configuration.ConfigurationManager.App設定屬性是取得應用程式設定值的替代 API,但建議您使用 GetEnvironmentVariable
,如下所示。
執行階段的繫結
在 C# 和其他 .NET 語言中,您可以使用命令式系結模式,而不是屬性中的宣告式系結。 當繫結參數需要在執行階段而不是設計階段中計算時,命令式繫結非常有用。 利用此模式,您可以快速在您的函式程式碼中繫結至支援的輸入和輸出繫結。
定義命令式繫結,如下所示︰
請勿 在函式簽章中包含所需命令式系結的屬性。
傳入輸入參數
Binder binder
或IBinder binder
。使用下列 C# 模式來執行資料繫結。
using (var output = await binder.BindAsync<T>(new BindingTypeAttribute(...))) { ... }
BindingTypeAttribute
是定義系結的 .NET 屬性,而T
是該系結類型支援的輸入或輸出類型。T
不能是out
參數類型 (例如out JObject
)。 例如,Mobile Apps 數據表輸出系結支援六種輸出類型,但您只能搭配命令式系結使用 ICollector<T> 或 IAsyncCollector<T>。
單一屬性範例
下列範例程式碼會使用在執行階段定義的 blob 路徑來建立儲存體 blob 輸出繫結,然後將字串寫入 blob。
public static class IBinderExample
{
[FunctionName("CreateBlobUsingBinder")]
public static void Run(
[QueueTrigger("myqueue-items-source-4")] string myQueueItem,
IBinder binder,
ILogger log)
{
log.LogInformation($"CreateBlobUsingBinder function processed: {myQueueItem}");
using (var writer = binder.Bind<TextWriter>(new BlobAttribute(
$"samples-output/{myQueueItem}", FileAccess.Write)))
{
writer.Write("Hello World!");
};
}
}
BlobAttribute 會定義儲存體 blob 輸入或輸出繫結,而 TextWriter 是支援的輸出繫結類型。
多個屬性範例
先前的範例會取得函數應用程式主要儲存體帳戶連接字串的應用程式設定 (也就是 AzureWebJobsStorage
)。 您可以指定要用於儲存體帳戶的自訂應用程式設定,方法是新增 StorageAccountAttribute 並將屬性陣列傳遞至 BindAsync<T>()
。 使用 Binder
參數,而不是 IBinder
。 例如:
public static class IBinderExampleMultipleAttributes
{
[FunctionName("CreateBlobInDifferentStorageAccount")]
public async static Task RunAsync(
[QueueTrigger("myqueue-items-source-binder2")] string myQueueItem,
Binder binder,
ILogger log)
{
log.LogInformation($"CreateBlobInDifferentStorageAccount function processed: {myQueueItem}");
var attributes = new Attribute[]
{
new BlobAttribute($"samples-output/{myQueueItem}", FileAccess.Write),
new StorageAccountAttribute("MyStorageAccount")
};
using (var writer = await binder.BindAsync<TextWriter>(attributes))
{
await writer.WriteAsync("Hello World!!");
}
}
}
觸發和繫結
此表顯示主要版本的 Azure Functions 執行階段中所支援的繫結:
類型 | 1.x1 | 2.x 和更高2 | 觸發程序 | 輸入 | 輸出 |
---|---|---|---|---|---|
Blob 儲存體 | ✔ | ✔ | ✔ | ✔ | ✔ |
Azure Cosmos DB | ✔ | ✔ | ✔ | ✔ | ✔ |
Azure 資料總管 | ✔ | ✔ | ✔ | ||
Azure SQL | ✔ | ✔ | ✔ | ✔ | |
Dapr4 | ✔ | ✔ | ✔ | ✔ | |
Event Grid | ✔ | ✔ | ✔ | ✔ | |
事件中樞 | ✔ | ✔ | ✔ | ✔ | |
HTTP 和 Webhook | ✔ | ✔ | ✔ | ✔ | |
IoT 中樞 | ✔ | ✔ | ✔ | ||
Kafka3 | ✔ | ✔ | ✔ | ||
行動應用程式 | ✔ | ✔ | ✔ | ||
通知中樞 | ✔ | ✔ | |||
佇列儲存體 | ✔ | ✔ | ✔ | ✔ | |
Redis | ✔ | ✔ | |||
RabbitMQ3 | ✔ | ✔ | ✔ | ||
SendGrid | ✔ | ✔ | ✔ | ||
服務匯流排 | ✔ | ✔ | ✔ | ✔ | |
SignalR | ✔ | ✔ | ✔ | ✔ | |
表格儲存體 | ✔ | ✔ | ✔ | ✔ | |
計時器 | ✔ | ✔ | ✔ | ||
Twilio | ✔ | ✔ | ✔ |
11.x 版 Azure Functions 執行階段支援將於 2026 年 9 月 14 日結束。 強烈建議您將應用程式移轉至 4.x 版,以取得完整支援。
2 從 2.x 版執行階段開始,必須註冊 HTTP 和計時器以外的所有繫結。 請參閱註冊繫結延伸模組。
3 觸發程序在取用方案中不受支援。 需要執行階段驅動的觸發程序。
4 僅在 Kubernetes、IoT Edge 和其他自我裝載模式中受到支援。