名称由单个下划线分隔的ASP.NET Core Options模式

时间:2019-09-03 14:12:37

标签: asp.net-core asp.net-core-configuration

我正在尝试使用ASP.NET Core Options模式加载应用程序设置。

<!DOCTYPE html> <html> <head> <title>This shows how to get elements inside included svg images from the surrounding html.</title> </head> <body> <object class="emb" data="borrowedpic.svg" width="100" height="100" type="image/svg+xml"></object> <embed class="emb" src="borrowedpic.svg" width="100" height="100" type="image/svg+xml" /> <iframe class="emb" src="borrowedpic.svg" width="100" height="100" style="border:0" ></iframe> <p> You should see three svg logo images with green fill above here. </p> <p> If any of the logos are shown in orange that means the browser failed to access the DOM of the referenced svg resource. From left to right we have &lt;object&gt;, &lt;embed&gt; and &lt;iframe&gt; that all reference the <a href="borrowedpic.svg">same svg file</a>. The script gets the referenced svg document either with <code>contentDocument</code> or <code>getSVGDocument()</code> and then sets the fill color to lime green. </p> <p> View source to see how this works. </p> <script>//<![CDATA[ // wait until all the resources are loaded window.addEventListener("load", findSVGElements, false); // fetches the document for the given embedding_element function getSubDocument(embedding_element) { if (embedding_element.contentDocument) { return embedding_element.contentDocument; } else { var subdoc = null; try { subdoc = embedding_element.getSVGDocument(); } catch(e) {} return subdoc; } } function findSVGElements() { var elms = document.querySelectorAll(".emb"); for (var i = 0; i < elms.length; i++) { var subdoc = getSubDocument(elms[i]) if (subdoc) subdoc.getElementById("svgbar").setAttribute("fill", "lime"); } } //]]> </script> </body> </html> 包含:

appsettings.json

POCO课程:

{
  "TEst": "hello",
  "TEST_ABC": "2" 
}

绑定到配置:

public class AppSetting
{
    public string Test { get; set; }

    public string TestAbc { get; set; }
}

在控制器中访问AppSetting实例时,我只能将配置services.Configure<AppSetting>(Configuration); 设为Testhello设置为TestAbc

“选项”模式似乎无法转换这种命名配置,是否可以通过其他任何方式来实现?

1 个答案:

答案 0 :(得分:1)

自动完成此操作的唯一方法是用下划线(Test_Abc)命名您的属性。除此之外,您可以手动指定映射:

services.Configure<AppSettings>(o => 
{
    o.TestAbc = Configuration["TEST_ABC"];
    // etc.
});

@DavidG关于使用[JsonProperty]的评论可能有效。我从未在配置上下文中尝试过。但是,只有在使用JSON配置提供程序时,它才可以使用(如果可以使用的话)。例如,如果以后需要通过环境变量来满足此要求,那么您就不走运了。因此,我会坚持使用比这更通用的解决方案。