如何在ASP.NET Core 6.0 Web API中读取Azure应用服务的应用设置

swvgeqrz  于 2023-01-14  发布在  .NET
关注(0)|答案(1)|浏览(137)

我正在开发一个.NET Core 6.0“Hello World”应用程序,它将被部署为Azure Web服务。
我正在尝试从Azure应用服务-〉配置-〉ApplicationSetting -〉mykey读取值,但在部署到应用服务后无法访问mykey的值。调试时,我可以在本地读取mykey的值。

项目类型:

我必须在Program.cs中读取mykey。既然它只是一个hello world应用程序,那么读取mykey的值的最简单方法是什么?
Program.cs

using HelloWorldApi.Helpers;
using Microsoft.AspNetCore.Authentication.Certificate;
using Microsoft.AspNetCore.Server.Kestrel.Https;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
    
var provider = builder.Services.BuildServiceProvider();
var configuration = provider.GetRequiredService<IConfiguration>();

builder.WebHost.ConfigureKestrel(o =>
{
    o.ConfigureHttpsDefaults(o =>
    {
    });
}).ConfigureAppConfiguration((hostContext, builder) =>
{
    var settings = builder.Build();

    // I tried different ways but not getting value of mykey. 
    // This code is returning null
    var connectionString = configuration.GetValue<string>("mykey");
});

var app = builder.Build();

pw9qyyiw

pw9qyyiw1#

请检查代码中的以下更改,以从Azure应用程序设置读取值。
Program.cs中,

正在使用代码检索值。

var AppsetVal = configuration.GetValue<string>("mykey")


来自示例代码

var AppsetVal = builder.Configuration.GetValue<string>("mykey");

我的appsettings.json文件:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*", 
  "mykey": "test"
}

Azure中的设置:

这里我显示的值在API控制器.

在天气预报控制器中. cs:

using Microsoft.AspNetCore.Mvc;

namespace WebApplication7.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {      
        private readonly ILogger<WeatherForecastController> _logger;
        private readonly IConfiguration Configuration;

        public WeatherForecastController(ILogger<WeatherForecastController> logger, IConfiguration configuration)
        {
            _logger = logger;
            Configuration = configuration;
        }

        [HttpGet(Name = "GetWeatherForecast")]
        public IEnumerable<WeatherForecast> Get()
        {
            //var MyAppSettings = Configuration.GetSection("AppSettings");

            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {              
                Date = DateTime.Now.AddDays(index),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)],
                myval = Configuration.GetSection("mykey").Value

            })
            .ToArray();
        }
    }
}

WeatherForecast.cs中,添加

public string? myval { get; set; }

部署的应用程序服务输出:

相关问题