gpt4 book ai didi

c# - 在订阅 Azure 应用程序配置中的更改的 Web API 中实现 Azure 事件网格事件处理程序

转载 作者:行者123 更新时间:2023-12-03 07:02:18 25 4
gpt4 key购买 nike

我正在探索从 Azure 应用程序配置获取配置数据的各种方法,并且大多数方法都有效,但是我正在努力在 ASP.NET Core 3.1 上的 Web API 中实现 Azure 事件网格事件处理程序。我想知道是否可以通过事件网格通知 Web API 有关更改,而不是在为 Azure 应用程序配置设置的缓存过期时进行轮询。一旦收到通知,配置值应该更新,并且当有人向 Web API 发出请求时,新值应该提供给任何 Controller 。

我已将内容包含在我的 Program.cs、Startup.cs、服务总线使用者中,我在其中设置了事件网格订阅者和示例 Controller 。

根据我从 Microsoft 文档中读到的内容,我的理解是 IConfigurationRefresher.ProcessPushNotification 方法将缓存过期重置为短暂的随机延迟,而不是在 CreateHostedBuilder 方法中以及 IConfigurationRefresher.TryRefreshAsync() 时设置的缓存过期。称为更新配置值。

我遇到的问题是无法将 IConfigurationRefresher 的具体类的实例注入(inject) RegisterRefreshEventHandler 方法,然后调用 ProcessPushNotification 来重置过期时间。

我也可能会错误地处理这个问题,因为我假设在控制台应用程序中工作的 RegisterRefreshEventHandler 代码也适用于 Web API。请告诉我我的方法是否有效?

程序.cs

   public class Program
{
private static IConfiguration _configuration;

private static IConfigurationRefresher _refresher;

public static void Main(string[] args)
{

_configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json", optional: false).Build();

CreateHostBuilder(args).Build().Run();

}

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
webBuilder.ConfigureAppConfiguration((hostingContext, config) =>
{
var settings = config.Build();
config.AddAzureAppConfiguration(options =>
{
options
.Connect(_configuration["AppConfig"]).ConfigureRefresh(
refresh => refresh.Register(key: "Api:Sentinel", refreshAll: true).SetCacheExpiration(TimeSpan.FromDays(1))

).Select(KeyFilter.Any, "ClientA");

_refresher = options.GetRefresher();
}
);
}).UseStartup<Startup>());
}

启动.cs

   public class Startup
{
public Startup(IConfiguration configuration, IConfigurationRefresher configurationRefresher)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<TFASettings>(Configuration.GetSection("Api:TFA"));
services.AddControllers();
services.AddAzureAppConfiguration();
services.AddSingleton<IServiceBusConsumer, ServiceBusConsumer>();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

var bus = app.ApplicationServices.GetRequiredService<IServiceBusConsumer>();
bus.RegisterRefreshEventHandler();

app.UseAzureAppConfiguration();

app.UseHttpsRedirection();

app.UseRouting();

app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}

ServiceBusConsumer.cs

    public class ServiceBusConsumer : IServiceBusConsumer
{

public IConfigurationRefresher configurationRefresher;

public ServiceBusConsumer()
{

}

public void RegisterRefreshEventHandler()
{
SubscriptionClient serviceBusClient = new SubscriptionClient("*****", "*****", "*****");

serviceBusClient.RegisterMessageHandler(
handler: (message, cancellationToken) =>
{
// Build EventGridEvent from notification message
EventGridEvent eventGridEvent = EventGridEvent.Parse(BinaryData.FromBytes(message.Body));

// Create PushNotification from eventGridEvent
eventGridEvent.TryCreatePushNotification(out PushNotification pushNotification);

//// Prompt Configuration Refresh based on the PushNotification
//configurationRefresher.ProcessPushNotification(pushNotification);

return Task.CompletedTask;
},
exceptionReceivedHandler: (exceptionargs) =>
{
Console.WriteLine($"{exceptionargs.Exception}");
return Task.CompletedTask;
});
}
}

示例 Controller

    [ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private readonly TFASettings _tfaSettings;

public WeatherForecastController(IOptionsSnapshot<TFASettings> tfaSettings)
{
_tfaSettings = tfaSettings.Value;
}

[HttpGet]
public WeatherForecast Get()
{

return new WeatherForecast
{
AuthenticationText = _tfaSettings.AuthenticationWording
};
}
}


最佳答案

您可以通过依赖注入(inject)获取IConfigurationRefresher的具体实例。您甚至可以从构造函数中调用 RegisterRefreshEventHandler()。您的 ServiceBusConsumer.cs 可能如下所示。

private IConfigurationRefresher _configurationRefresher;

public ServiceBusConsumer(IConfigurationRefresherProvider refresherProvider)
{
_configurationRefresher = refresherProvider.Refreshers.FirstOrDefault();
RegisterRefreshEventHandler();
}

关于c# - 在订阅 Azure 应用程序配置中的更改的 Web API 中实现 Azure 事件网格事件处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72133747/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com