在 Azure 上用 C# 创建无服务器函数需选用 .NET 6+ 隔离模型,通过触发器(如 HTTP)、绑定(如 Blob)和生命周期管理实现免运维集成,本地开发后一键部署至 Function App 并自动集成 Application Insights。

在 Azure 上用 C# 创建无服务器函数,核心是使用 Azure Functions SDK(基于 .NET 6/7/8 的隔离模型或经典的进程内模型),配合 Visual Studio 或 VS Code 开发,再部署到 Azure。关键不在于“写代码”,而在于理解触发器、绑定和生命周期——这些决定了函数怎么被调用、数据怎么进出。
选择正确的项目模板和运行模型
Azure Functions 支持两种主流 .NET 模型:
-
隔离进程模型(.NET Isolated):推荐用于新项目,.NET 6+,独立于宿主进程运行,支持完整 .NET API,配置更直观,通过
FunctionApp项目模板创建; - 进程内模型(In-process):仅限 .NET Framework 或 .NET Core 3.1/.NET 5(已过时),与 Functions 主机共享进程,性能略高但限制多,不建议新项目使用。
在 VS Code 中安装 Azure Functions 扩展后,运行 func init 并选择 .NET Isolated;在 Visual Studio 中新建项目时选 Azure Functions 模板,并确认目标框架为 .NET 6 或更高版本。
编写一个 HTTP 触发的函数
以最常用的 HTTP 函数为例,创建后默认会生成类似下面的代码:
public static class HttpExample
{
[Function("HttpExample")]
public static HttpResponseData Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req,
FunctionContext executionContext)
{
var logger = executionContext.GetLogger("HttpExample");
logger.LogInformation("C# HTTP trigger function processed a request.");
var response = req.CreateResponse(HttpStatusCode.OK);
response.Headers.Add("Content-Type", "text/plain; charset=utf-8");
response.WriteString("Hello from Azure Functions with .NET Isolated!");
return response;
}}
注意点:
- 必须用
[Function("Name")]特性标记方法,名称将作为函数路由的一部分; -
HttpRequestData和HttpResponseData是隔离模型专用类型,不是传统的HttpRequest/HttpResponse; - 日志通过
FunctionContext.GetLogger()获取,自动集成 Application Insights; - 本地调试直接按 F5,函数会启动本地 host,URL 类似
http://localhost:7071/api/HttpExample。
添加输入/输出绑定(比如读写 Blob 或队列)
无服务器的关键优势是免运维集成。例如,让函数自动处理上传到 Blob Storage 的图片:
- 在方法参数中添加
[BlobInput("sample-images/{name}", Connection = "StorageConnectionString")] BinaryData blob,即可自动加载指定路径的文件; - 用
[BlobOutput("processed-images/{rand-guid}.jpg", Connection = "StorageConnectionString")] out byte[] output写入结果; - 连接字符串需在
local.settings.json(本地)或 Azure Function App 的 配置 → 应用设置 中定义,键名为StorageConnectionString; - 绑定支持多种服务:Service Bus、Event Hubs、Cosmos DB、SQL(预览)、SendGrid 等,只需 NuGet 引入对应扩展包(如
Microsoft.Azure.Functions.Worker.Extensions.Storage)。
部署到 Azure 并验证
部署本质是把编译后的函数应用发布到 Azure Function App 实例:
- 确保已登录 Azure CLI(
az login)或在 VS/VS Code 中配置好账户; - 右键项目 → Publish → 选择 Azure Function App (Windows/Linux) → 新建或选择已有实例;
- 部署成功后,访问
https://即可调用(HTTP 函数需注意认证级别,.azurewebsites.net/api/ AuthorizationLevel.Function需带?code=xxx查询参数,密钥可在 Azure 门户的函数详情页获取); - 所有日志自动流向 Application Insights,可在门户中实时查看执行时间、失败原因、依赖调用等。
基本上就这些。不需要管理服务器、扩缩容或补丁更新——你只关注业务逻辑,Azure 负责其余一切。










