Knu*_*ius 2 asp.net-mvc configuration appsettings asp.net-mvc-4
在创建ASP.Net MVC应用程序时,我有一个问题让我感到震惊:假设您有一个应用程序要部署到多个客户.应用程序代码是相同的,但您希望每个客户都能拥有一个appSettings.config文件,这样您只需更改web.config中appSettings标记的configSource即可部署到不同的客户(稍微简化一下) ,但仍然).
然后您意识到appSettings.config中50%的内容对所有客户都是通用的,只有50%是依赖于客户的.您可能最终要做的是在所有appSettings文件中都有重复的条目,这是一个主要的缺陷,因为如果您想对应用程序进行应用程序范围的更改,则需要记住更新所有这些条目.
在这种情况下,我真的希望有一种分层系统,你可以在单独的文件中有一个"基本配置"和"客户配置".然后我希望ConfigurationManager首先检查客户配置中的值,如果没有在那里定义它,它将转到基本配置.
我没有找到一种直接的解决方法,使用ASP.Net MVC4中的开箱即用功能.它是退出的,还是我需要以某种方式绕过默认的ConfigurationManager类?我可以创建自己的类,并通过调用我自己的实现来替换对ConfigurationManager.AppSettings [key]的所有调用,但如果可以的话,我宁愿避免这样做.我希望能够使用内置ConfigurationManager负责的一些基本功能,如缓存等.
以前解决过类似问题的人?我一直认为这似乎是一种常见的情况..
这是一种常见的情况,有不同的解决方法.一种方法是使用配置转换.你可以有一个Web.Customer1.config,Web.Customer2.config等等,就像你有Web.Debug.config和Web.Release.config.在客户特定的转换文件中,您只能"覆盖" appSettings客户想要自定义的转换文件.
要创建不同的转换,首先要创建不同的项目平台.转到Visual Studio配置管理器,在ConfigurationWeb项目的列(或任何需要自定义配置设置的项目)中,单击下拉列表,然后单击<New...>.将新项目配置命名为Customer1您想要的任何内容,选中相应的复选框Copy settings from,然后Release从该下拉列表中选择.同时选中Create new solution configurations复选框.
最后,右键单击您的web.config文件并单击Add config transform.这将为您生成模板Web.Customer1.config文件.appSettings使用xdt:config transform属性编辑它以覆盖它所需的内容.然后,您可以使用Customer1解决方案构建配置发布项目.作为构建的一部分,web.config将进行转换,您将最终web.config为每个客户提供不同的文件.您还可以使用它来自定义不同部署的项目,即更改数据库连接字符串,smtp服务器,XML配置文件中的任何内容.
最后一点,请确保右键单击每个Web.Xyx.config文件,选择属性并将其设置Build Action为None.
例:
base web.config
<appSettings>
<add key="CommonProperty1" value="[for all customers]" />
<add key="CommonProperty2" value="[for all customers]" />
<add key="CommonProperty3" value="[for all customers]" />
<add key="CustomProperty1" value="[for one customer]" />
<add key="CustomProperty2" value="[for one customer]" />
<add key="CustomProperty3" value="[for one customer]" />
<appSettings>
Run Code Online (Sandbox Code Playgroud)
web.Customer1.config
<appSettings>
<add key="CustomProperty1" value="The Ohio State University" xdt:Transform="SetAttributes" xdt:Locator="Match(key)" />
<add key="CustomProperty2" value="Scarlet" xdt:Transform="SetAttributes" xdt:Locator="Match(key)" />
<add key="CustomProperty3" value="Gray" xdt:Transform="SetAttributes" xdt:Locator="Match(key)" />
<appSettings>
Run Code Online (Sandbox Code Playgroud)
web.Customer2.config
<appSettings>
<add key="CustomProperty1" value="Michigan University" xdt:Transform="SetAttributes" xdt:Locator="Match(key)" />
<add key="CustomProperty2" value="Blue" xdt:Transform="SetAttributes" xdt:Locator="Match(key)" />
<add key="CustomProperty3" value="Maize" xdt:Transform="SetAttributes" xdt:Locator="Match(key)" />
<appSettings>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1784 次 |
| 最近记录: |