如何使用.NET Azure Management SDK更新App Service证书
结论
.NET 版 Azure Resource Manager v1.1 管理 SDK 完全支持App Service新证书上传、旧TLS绑定删除、新TLS绑定创建全流程操作。你没找到私有站点证书相关方法,是因为这类操作没有直接挂在Web App资源的操作入口下,而是归类在App Service服务管理器的证书资源集合中。
前置依赖
- 项目需引入对应版本的NuGet包:
Microsoft.Azure.Management.AppService.Fluent1.1.x、Microsoft.Azure.Management.ResourceManager.Fluent用于认证和资源操作 - 提前完成Azure AD认证,拿到可操作目标资源的
IAzure实例,操作账号/服务主体需至少拥有目标资源组的Website Contributor权限
具体实现步骤
1. 上传新私有站点证书
通过Web App实例对应的Manager入口访问证书操作集合完成上传,注意证书区域必须和目标App Service所属区域一致:
// 读取本地PFX证书文件 byte[] pfxContent = File.ReadAllBytes(@"C:\certs\your-new-cert.pfx"); string pfxPassword = "your-cert-private-key-password"; // 上传证书到指定资源组 var newCert = await azure.WebApps.Manager.Certificates .Define("new-cert-2024") // 自定义证书在Azure中的资源名称 .WithRegion(Region.ChinaNorth3) // 替换为你的App Service所在区域 .WithExistingResourceGroup("your-app-rg") // 替换为你的资源组名称 .WithPfxByteArray(pfxContent) .WithPfxPassword(pfxPassword) .CreateAsync(); // 记录证书指纹,后续绑定时使用 string newCertThumbprint = newCert.Thumbprint;
2. 删除旧TLS绑定
先拉取目标App Service实例,移除对应域名的旧SSL绑定即可,如果需要同步清理旧证书资源,可在解绑完成后调用证书删除接口:
var targetWebApp = await azure.WebApps .GetByResourceGroupAsync("your-app-rg", "your-app-service-name"); var appUpdate = targetWebApp.Update(); // 移除指定域名的旧TLS绑定,参数替换为你实际绑定的自定义域名 appUpdate = appUpdate.WithoutSslBinding("blog.yourdomain.com"); // 如需删除旧证书,传入旧证书的资源ID执行删除即可 // await azure.WebApps.Manager.Certificates.DeleteByIdAsync("/subscriptions/xxx/resourceGroups/xxx/providers/Microsoft.Web/certificates/old-cert-2023"); var appAfterUnbind = await appUpdate.ApplyAsync();
3. 新建TLS绑定
基于新上传证书的指纹,给目标域名创建新的SSL绑定,可根据业务需求选择SNI模式或IP模式:
var finalUpdate = appAfterUnbind.Update() .DefineSslBinding() .ForHostname("blog.yourdomain.com") // 要绑定证书的自定义域名 .WithExistingCertificate(newCertThumbprint) // 传入新证书的指纹 .WithSniBasedSsl() // 如需IP绑定模式,替换为 .WithIpBasedSsl() .Attach(); // 提交更新完成所有操作 await finalUpdate.ApplyAsync();
注意:所有操作涉及的资源组、区域必须和目标App Service实例保持一致,否则会出现证书上传后找不到、绑定失败的问题。如果你的App Service部署在隔离的ASE环境中,需要额外指定ASE对应的部署参数。
内容的提问来源于stack exchange,提问作者navitiello
相关产品推荐
相关产品推荐

