我需要为 WebJobs 执行一些管理 API 代码,发现现在可以了,尽管在 API 文档中很难找到。
你可以通过安装Microsoft.Azure.Management.AppService.Fluent包来做到这一点(我认为非流利的管理SDK也可以做到这一点,虽然我没有尝试过)。
可以像这样访问管理 WebJob 的方法:
using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Authentication;
class MyWebJobsManagementClass
{
public async Task DoSomeWebJobsManagement()
{
var jobs = await Azure
.Authenticate() // See the docs for how to authenticate with this SDK
.WithSubscription("your-subscription-id")
.AppServices
.Inner
.WebApps
.ListWebJobsWithHttpMessagesAsync("resource-group-name", "app-service-name")
}
}
通过不明显的AppServices.Inner,您可以获得对IWebAppsOperations 实例的引用,然后您可以在WebJobs 上执行相当多的操作,包括启动和停止它们。
身份验证附注
如果您正在寻找一种使用 Azure.Identity 进行身份验证的方法,而不是他们过去用于这些旧 SDK 的基于文件的凭据方法,那么即使不支持“out-盒子”。
有一个GitHub repo 包含如何实现此目的的示例。我认为它是由 Microsoft 团队的一位开发人员提供的,但并未得到 Microsoft 的正式支持。它没有 NuGet 包,他们建议只复制您需要的位。
我实际上发现该示例存储库中的代码对于我的需求来说过于复杂,而在我的情况下,我所需要的就是这个。 请注意,我是从我的 F# 项目中复制的,没有对其进行测试,所以我在转换为 C# 时可能会出错,但希望它足够接近,您可以理解。
class AzureIdentityFluentCredentialAdapter : AzureCredentials
{
public AzureIdentityFluentCredentialAdapter(string tenantId)
: base(default(DeviceCredentialInformation), tenantId, AzureEnvironment.AzureGlobalCloud)
{
}
public override Task ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var creds = DefaultAzureCredential() // Use the new Azure.Identity library to get access tokens
var accessToken = await creds.GetTokenAsync(
new TokenRequestContent(new [] { "https://management.azure.com/.default" }),
cancellationToken);
return await TokenCredentials(accessToken.Token)
.ProcessHttpRequestAsync(request, cancellationToken);
}
}
这个例子没有做任何令牌缓存,但出于我的目的,我并没有太在意这个。它还对我请求令牌的范围进行了硬编码,因为我知道我只会将它与 Azure 管理 API 一起使用。