【问题标题】:How to access Azure app service settings/configuration in .NET 6? [duplicate]如何在 .NET 6 中访问 Azure 应用服务设置/配置? [复制]
【发布时间】:2022-02-27 01:29:36
【问题描述】:

我有一个在 Azure 中运行的 Web 应用程序,该应用程序当前在 .NET 5 上运行,我正在尝试将其升级到 6。我已重构代码以删除 Startup.cs 文件并重构 Program.cs 以适应.NET 6 应用程序的新结构。在其他人告诉我两个文件的旧方法仍然有效之前,是的,我知道,但我想转向新标准,以便它可以作为未来应用程序的模板,默认情况下,第一次在 VS 中创建时只使用一个文件。

在现有的Startup.cs 文件中,我有这样的内容:

using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Identity.Web;

namespace MyApp.Web.Server
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
                .AddMicrosoftIdentityWebApp(Configuration.GetSection(Constants.AzureAdB2C))
                .EnableTokenAcquisitionToCallDownstreamApi(new string[] { "https://example.com/api/query" })
                .AddInMemoryTokenCaches();

            // Other services added here
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");

                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(
                endpoints =>
                    {
                        endpoints.MapControllers();
                        endpoints.MapBlazorHub();
                        endpoints.MapFallbackToPage("/_Host");
                    });
        }
    }
}

当调用Startup 构造函数时,会注入一个IConfiguration 实例,据我所知,这是在DevOps 上运行时动态完成的,以包括在应用服务-> 设置-> 配置-> 应用程序中设置的所有应用程序设置设置页面。目前一切正常。

但是,使用 .NET 6 语法的新 Program.cs 文件如下所示:

using System.Reflection;

using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.Identity.Web;

IConfiguration configuration;

WebApplicationBuilder builder = WebApplication.CreateBuilder(args);

string appSettingsPath = Path.Combine(
    Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
    "appsettings.json");

configuration = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile(appSettingsPath, optional: false, reloadOnChange: true)
    .Build();

builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(configuration.GetSection(Constants.AzureAdB2C))
    .EnableTokenAcquisitionToCallDownstreamApi(new string[] { "https://example.com/api/query" })
    .AddInMemoryTokenCaches();

// Other services added here

WebApplication app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}
else
{
    app.UseExceptionHandler("/Error");

    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.UseEndpoints(
    endpoints =>
    {
        endpoints.MapControllers();
        endpoints.MapBlazorHub();
        endpoints.MapFallbackToPage("/_Host");
    });

app.Run();

正如您在上面看到的,没有构造函数,因此我无法注入 IConfiguration 实例,所以目前我假设有一个 appsettings.json 文件并从中创建它。这在 Azure 环境中运行时不起作用,因为仪表板中指定的设置不会添加到 appsettings.json 文件中,它们被设置为环境变量。

我可以检索环境变量,但我无法检索变量组,这是添加Microsoft.Identity 身份验证的特殊情况下的要求。有没有办法像以前一样动态解析/注入IConfiguration 实例?

【问题讨论】:

    标签: c# azure asp.net-core azure-web-app-service .net-6.0


    【解决方案1】:

    原来是我想多了。我认为 Azure 应用服务运行时仍在创建和/或动态添加一个 IServiceCollection,因此尝试删除所有试图创建 IConfiguration 实例的代码,并假设在创建.NET 6 WebApplicationBuilder 实例。

    果然有。我需要做的就是引用 builder.Configuration 实例,它已经从 Azure 容器中注入了 IConfiguration

    using Microsoft.AspNetCore.Authentication.OpenIdConnect;
    using Microsoft.Identity.Web;
    
    WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
    
    builder.Services.AddApplicationInsightsTelemetry();
    
    builder.Services.AddRazorPages();
    
    builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
        .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection(Constants.AzureAdB2C))
        .EnableTokenAcquisitionToCallDownstreamApi(new string[] { "https://example.com/api/query" })
        .AddInMemoryTokenCaches();
    
    builder.Services.Configure<OpenIdConnectOptions>(builder.Configuration.GetSection("AzureAdB2C"));
    
    // Other services added here
    
    WebApplication app = builder.Build();
    
    if (app.Environment.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
    
        app.UseHsts();
    }
    
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    
    app.UseRouting();
    
    app.UseAuthentication();
    app.UseAuthorization();
    
    app.UseEndpoints(
        endpoints =>
        {
            endpoints.MapControllers();
            endpoints.MapBlazorHub();
            endpoints.MapFallbackToPage("/_Host");
        });
    
    app.Run();
    

    仅供参考,如果您像我一样有本地 appsettings.json 文件用于在调试或测试中运行,我在帮助程序类中有以下方法:

    public static IConfiguration GetConfigurationFromAssembly(string appSettingsFileName)
    {
        Assembly dataAssembly = Assembly.LoadFrom(
            Path.Combine(
            
        Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                        "MyApp.Web.Data.dll")); // Put your own project DLL containing the embedded resource here
    
        Stream jsonStream =
            dataAssembly.GetManifestResourceStream($"MyApp.Web.Data.{appSettingsFileName}");
    
        return new ConfigurationBuilder()
            .AddJsonStream(jsonStream)
            .SetBasePath(Directory.GetCurrentDirectory())
            .Build();
    }
    
    public static IConfiguration GetConfigurationFromFile(string appSettingsFileName)
    {
        string appSettingsPath = Path.Combine(
            Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
            appSettingsFileName);
    
        return new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile(appSettingsPath, optional: false, reloadOnChange: true)
            .Build();
    }
    

    然后您可以像这样将返回的IConfiguration 对象添加到WebApplicationBuilder

    WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
    
    #if DEBUG
    configuration = Configurations.GetConfigurationFromAssembly("appsettings.Development.json");
    
    builder.Configuration.AddConfiguration(configuration);
    #endif
    
    builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
        .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection(Constants.AzureAdB2C))
        .EnableTokenAcquisitionToCallDownstreamApi(new string[] { "https://example.com/api/query" })
        .AddInMemoryTokenCaches();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-23
      • 2019-04-09
      • 2021-09-05
      • 1970-01-01
      • 2018-08-21
      • 2017-06-16
      • 1970-01-01
      • 2019-09-06
      相关资源
      最近更新 更多