我无法让Configuration.GetSection
在.Value
中返回数据。我认为我实施了question的所有建议,但仍无法使其发挥作用。
appsettings.json
{
"AmazonSettings": {
"BaseUrl": "https://testing.com",
"ClientID": "123456",
"ResponseType": "code",
"RedirectUri": "https://localhost:44303/FirstTimeWelcome"
},
}
启动:
public IConfiguration Configuration { get; }
public Startup(IHostingEnvironment env)
{
//Set up configuration sources.
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
ConfigurationServices:
public void ConfigureServices(IServiceCollection services)
{
services.AddOptions();
services.Configure<AmazonSettings>(Configuration.GetSection("AmazonSettings"));
services.AddMvc()
AmazonSettings类:
public class AmazonSettings
{
public string BaseUrl { get; set; }
public string ClientID { get; set; }
public string RedirectUri { get; set; }
public string ResponseType { get; set; }
}
我试图通过IOptions访问AmazonSettings.Value:
public class HomeController : Controller
{
private readonly AmazonSettings _amazonSettings;
public IActionResult Index()
{
ViewBag.LoginUrl = _amazonSettings.BaseUrl;
return View("/Pages/Index.cshtml"); ;
}
public HomeController(IOptions<AmazonSettings> amazonSettings)
{
_amazonSettings = amazonSettings.Value;
}
当我调试时,Value为空:
答案 0 :(得分:0)
我的问题是HomeController中的代码从未受到过攻击。
我可以到达那里,并且.Value已填充,如果我在控制器上方添加了路由[&#34; home&#34;]并导航到localhost / home。我无法使用路由[&#34;&#34;]但是因为我使用了Razor页面而导致了一个模糊的异常。
然后我意识到我根本不需要使用Razor Pages的控制器。我可以直接从Index.cshtml.cs
访问我的数据public class IndexModel : PageModel
private readonly AmazonSettings _amazonSettings;
public string LoginUrl;
public IndexModel(IOptions<AmazonSettings> amazonSettings)
{
_amazonSettings = amazonSettings.Value;
}
在我的Index.cshtml页面中具有以下访问权限:
<a href=@Model.LoginUrl><h1>@Model.LoginUrl</h1></a>
事实证明,在调试时,GetSection在启动代码中返回的.Value可能为null,但它会在到达IndexModel时填充。