从代码(c#)部署Azurefunction

如何将代码为字符串(在c#中)的azure函数(按计划执行)部署到给定的azure函数应用程序?

我将使用ARM模板部署azure fund app(+所有它需要的) https://github.com/Azure/azure-quickstart-templates/tree/master/101-function-app-create-dynamic ,它可以通过代码部署;

但我没有看到通过代码部署function到应用程序的方法。

+更多上下文 :部署将从应用服务发生,因此除了NuGet之外,最好不要有任何依赖。 例如,我不喜欢从c#调用azure cli的想法。

正如Jesse Carter所说,我们可以使用Kudu Zip Api来做到这一点。 我做了一个演示。 它在我身边正常工作。 以下是我的详细步骤:

制备:

注册一个AD应用程序并为applcation分配角色,更多细节请参考Azure官方教程 。 之后我们可以从Azure门户获取tenantId,appId,secretKey。

1.准备一个认证文件,我们可以从github 文件中获取更多信息。

subscription=########-####-####-####-############ client=########-####-####-####-############ tenant=########-####-####-####-############ managementURI=https\://management.core.windows.net/ baseURL=https\://management.azure.com/ authURL=https\://login.windows.net/ graphURL=https\://graph.windows.net/ 

2.Zip需要发布文件

脚步:

1.创建一个C#控制台项目

2.参考Microsoft.Azure.Management.ResourceManager.Fluent和Microsoft.Azure.Management.AppService.Fluent ,更多详细信息请参阅packages.config文件部分。

3.在Program.cs文件中添加以下代码

  var credentials = SdkContext.AzureCredentialsFactory.FromFile(@"authentication file path"); var azure = Azure .Configure() .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic) .Authenticate(credentials) .WithDefaultSubscription(); var webFunctionAppName = "azure function name"; var webFunctionApp = azure.AppServices.FunctionApps.List().Where(x => x.Name.Equals(webFunctionAppName))?.First(); var ftpUsername = azure.AppServices.FunctionApps.GetById(webFunctionApp.Id).GetPublishingProfile().FtpUsername; var username = ftpUsername.Split('\\').ToList()[1]; var password = azure.AppServices.FunctionApps.GetById(webFunctionApp.Id).GetPublishingProfile().FtpPassword; var base64Auth = Convert.ToBase64String(Encoding.Default.GetBytes($"{username}:{password}")); var file = File.ReadAllBytes(@"zip file path"); MemoryStream stream = new MemoryStream(file); using (var client = new HttpClient()) { client.DefaultRequestHeaders.Add("Authorization", "Basic " + base64Auth); var baseUrl = new Uri($"https://{webFunctionAppName}.scm.azurewebsites.net/"); var requestURl = baseUrl+ "api/zip/site/wwwroot"; var httpContent = new StreamContent(stream); var response = client.PutAsync(requestURl, httpContent).Result; } 

4.来自当地的测试

在此处输入图像描述

5.检查Azure kudu工具发布的结果( https://yourazurefunctionanme.scm.azurewebsites.net/

在此处输入图像描述

packages.config

                          

如果您要直接从代码部署函数本身而不是使用CI / CD管道,那么最好的办法是使用Kudu REST API将函数代码作为zip上传到正在运行的函数应用程序。 您应该能够使用HttpClient或任何其他.NET REST库。