使用Azure应用程序配置的.NET 5 Web应用程序的动态配置不起作用

发布于 2025-02-06 12:00:32 字数 4446 浏览 3 评论 0 原文

我有一个问题,试图为我的.NET 5.0简单Web应用程序实现动态配置(用C#编写)。

问题:我运行我的应用程序,然后转到此应用程序的Azure应用程序配置并更改某些配置设置(例如页面的背景颜色),然后刷新我的页面,我看不到应用更改。

我拥有的内容:

  • 我有一个 azure应用程序配置,其中“配置资源管理器”中我设置了这些值(Sentinel键设置为值1):

  • 我有一个简单的'Hello World'Web App :

    program.cs [无法将其粘贴到代码,出于某种原因stackoverflow格式化了它]:

    其中的配置:azureconnectionsstring是我的Azure应用程序配置中找到的连接字符串(它具有正确的连接字符串,并且一切正常在此部分)

    startup.cs

    公共类启动 { 公共启动(IconFiguration配置) { 配置=配置; } 公共ICONFIGURATION配置{get; }

      //此方法由运行时调用。使用此方法将服务添加到容器中。
     公共Void Configureservices(IservCollection Services)
     {
         services.addcontrollers();
         Services.AddrazorPages();
         services.configure< settings>(configuration.getSection(“ testapp:settings”));
         services.AddControllersWithViews();
         Services.AddazureAppConfiguration();
     }
    
     //此方法通过运行时调用。使用此方法配置HTTP请求管道。
     公共void配置(iapplicationbuilder应用程序,iwebhostenvironment env)
     {
         如果(Env.ISDEVEVEMEMT())
         {
             app.usedeveloveerexceptionpage();
         }
         别的
         {
             app.usexceptionhandler(“/error”);
             //默认的HST值为30天。您可能需要将其更改为生产方案,请参阅https://aka.ms/aspnetcore-hsts。
             app.usehsts();
         }
    
         app.useazureappconfiguration();
         App.UseHttPsRedirection();
         app.usestaticfiles();
         app.userouting();
    
         app.useauthorization();
    
         App.UseEndPoints(endpoints =>
         {
             endpoints.maprazorpages();
         });
     }
     

    }

homecontroller.cs

public class HomeController : Controller
{
    private readonly Settings _settings;
    private readonly ILogger<HomeController> _logger;

    public HomeController(ILogger<HomeController> logger, IOptionsSnapshot<Settings> settings)
    {
        _logger = logger;
        _settings = settings.Value;
    }

    public IActionResult Index()
    {
        ViewData["BackgroundColor"] = _settings.BackgroundColor;
        ViewData["FontSize"] = _settings.FontSize;
        ViewData["FontColor"] = _settings.FontColor;
        ViewData["Message"] = _settings.Message;

        return View();
    }

    // ...
}

settings.cs

public class Settings
{
    public string BackgroundColor { get; set; }
    public long FontSize { get; set; }
    public string FontColor { get; set; }
    public string Message { get; set; }
}

index.cshtml

@page
@model IndexModel

@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration

<style>
    body {
        background-color: @ViewData["TestApp:Settings:BackgroundColor"]
    }
    h1 {
        
        font-size: @ViewData["TestApp:Settings:FontSize"];
    }
</style>
<div class="text-center">
    <h1 class="display-4">Hello World</h1>
    <p>Learn about <a href="https://learn.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
    <h1>
        @Configuration["TestApp:Settings:Message"]
    </h1>
</div>

发生了什么:一切都正确地显示了,但是,正如我提到的,例如,如果我更改,例如testapp:设置:消息和刷新页面,则没有应用更改(仅在我重新启动应用程序之后)

我尝试过的: 我在startup.cs中知道 app.useendpoints(),我应该这样做:

app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });

但是当我这样做时,我会得到此错误:

notes :我不知道为什么,但是当我在index.cshtml中使用@viewdata进行检索配置值(当前是当前的),即使我重新启动应用程序背景颜色更改不会应用,其他所有内容都将被应用(尝试将值作为单词,例如“黑色”或“蓝色”,以及Hex值,相同的结果)。当我使用@configuration而不是@viewdata时,应用背景颜色更改会

在这里有些丢失...有人知道如何使我的应用程序应用Azure应用程序配置动态更改吗?如您从program.cs所看到的那样,cacheexpiration设置为10s,因此应在10s之后应用更改,但它们不会 提前致谢!

I have an issue trying to implement dynamic config for my .NET 5.0 simple web app (written in C#).

The problem: I run my app, then go to Azure App Config for this app and change some config setting (like the background color of the page), then refresh my page and I don't see the changes being applied.

What I have:

  • I have an Azure App Configuration, where in the 'configuration explorer' I set these values (Sentinel key is set to value 1):
    enter image description here

  • I have a simple 'Hello World' Web app:

    Program.cs [couldn't paste it as code, for some reason stackoverflow formatted it weirdly]:
    enter image description here

    Where Configuration:AzureConnectionString is the connection string found in my Azure App Configuration (it has the correct connection string and everything works fine for this part)

    Startup.cs:

    public class Startup
    {
    public Startup(IConfiguration configuration)
    {
    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.AddControllers();
         services.AddRazorPages();
         services.Configure<Settings>(Configuration.GetSection("TestApp:Settings"));
         services.AddControllersWithViews();
         services.AddAzureAppConfiguration();
     }
    
     // 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();
         }
         else
         {
             app.UseExceptionHandler("/Error");
             // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
             app.UseHsts();
         }
    
         app.UseAzureAppConfiguration();
         app.UseHttpsRedirection();
         app.UseStaticFiles();
         app.UseRouting();
    
         app.UseAuthorization();
    
         app.UseEndpoints(endpoints =>
         {
             endpoints.MapRazorPages();
         });
     }
    

    }

HomeController.cs:

public class HomeController : Controller
{
    private readonly Settings _settings;
    private readonly ILogger<HomeController> _logger;

    public HomeController(ILogger<HomeController> logger, IOptionsSnapshot<Settings> settings)
    {
        _logger = logger;
        _settings = settings.Value;
    }

    public IActionResult Index()
    {
        ViewData["BackgroundColor"] = _settings.BackgroundColor;
        ViewData["FontSize"] = _settings.FontSize;
        ViewData["FontColor"] = _settings.FontColor;
        ViewData["Message"] = _settings.Message;

        return View();
    }

    // ...
}

Settings.cs :

public class Settings
{
    public string BackgroundColor { get; set; }
    public long FontSize { get; set; }
    public string FontColor { get; set; }
    public string Message { get; set; }
}

Index.cshtml :

@page
@model IndexModel

@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration

<style>
    body {
        background-color: @ViewData["TestApp:Settings:BackgroundColor"]
    }
    h1 {
        
        font-size: @ViewData["TestApp:Settings:FontSize"];
    }
</style>
<div class="text-center">
    <h1 class="display-4">Hello World</h1>
    <p>Learn about <a href="https://learn.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
    <h1>
        @Configuration["TestApp:Settings:Message"]
    </h1>
</div>

What happens: Everything is displayed correctly, but as I mentioned if I change, for example, TestApp:Settings:Message and refresh the page, the changes are not applied (only after I restart the app)

What I tried:
I know in Startup.cs, where I do app.UseEndpoints(), I should do it like this:

app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });

But when I do that, I get this error:
enter image description here

Notes : I don't know why, but when I use @ViewData in index.cshtml for retrieving config values (like it currently is), even when I restart the app the background color changes don't get applied, everything else gets applied (tried putting the value as word, like 'black' or 'blue' and also as hex values, the same result). When I use @Configuration instead of @ViewData, the background color change gets applied

I am a little lost here...Does anyone know how I can make my app apply the Azure App Config changes dynamically? As you can see from Program.cs, the CacheExpiration is set to 10s, so changes should get applied after 10s, but they don't
Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

如何视而不见 2025-02-13 12:00:33

Azure应用程序配置仅监视更改的前哨值,而不是其余的配置值。

这两者都可以使您准备几个更改,然后在更改前哨时原子应用它们,并减少监视许多设置的开销。

https://lealen.microsoft.com/en-us/azure/azure-app-configuration/enable-dynamic-configuration-configuration-configuration-core-core?tabs=core5x #add-a-a-a-a-sentinel-key < /a>

Azure App Configuration only monitors the sentinel value(s) for change, not the rest of your configuration values.

This both allows you to prepare several changes and then apply them atomically when you alter the sentinel, as well as reduces the overhead of monitoring many settings.

https://learn.microsoft.com/en-us/azure/azure-app-configuration/enable-dynamic-configuration-aspnet-core?tabs=core5x#add-a-sentinel-key

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文