Asp.net

從 web.config applicationSettings 獲取值到 ASP.NET 標記中

  • March 7, 2014

我現在可能完全偏離了軌道,所以我會在這裡問這個,以便有人可以幫助我。

我想要做的是將儲存在 applicationSettings 區域中的 web.config 中的值插入到我的 aspx 標記中。具體來說,我想從配置中讀取一個 URL。這是我使用的 configSection 設置

<configSections>  
<sectionGroup name="applicationSettings"  type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=123456">
 <section name="MyApp.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=12345" requirePermission="false" />
</configSections>

稍後在該文件中是實際設置,如下所示:

<applicationSettings>
<MyApp.Properties.Settings>
 <setting name="ImagesUrl" serializeAs="String">
   <value>http://resources/images/</value>
 </setting>

現在我想在標記中引用上面的值,如下所示:

<asp:Image ID="Image1" runat="server" ImageUrl="<%$AppSettings:ImagesUrl%>/Image1.jpg

我知道有一個可用的表達式 <%$ AppSettings: ImagesUrl %>,但我沒有使用 web.config 的 appsettings 部分,而是使用 configSection。

編輯:我相信我只能使用 ExpressionBuilder 來完成,因為我必須將字元串與單個圖像名稱連接起來。我更改了上面的範例以反映這一點。

我喜歡下面的 Bert Smith 程式碼解決方案來訪問配置部分,只是我需要將它放在表達式建構器中。我一直在重寫 GetCodeExpression 方法,我將從那裡呼叫配置管理器,但我不明白如何建構參數表達式。

public class SettingsExpressionBuilder: ExpressionBuilder
{
   public override CodeExpression GetCodeExpression(BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context)
   {
       return ??
   }

編輯

結果看起來像這樣,適用於各種文件,而不僅僅是圖像:

&lt;asp:ScriptReference Path='&lt;%$Code:GetAppSetting("ResourcesUrl","JS/jquery/jquery.jqplot.js")%&gt;'

我只是使用 Microsoft 的範例從表達式生成器返回任何類型的程式碼:

return new CodeSnippetExpression(entry.Expression);

GetAppSetting 是我的自定義 Page 類中的一種方法。

通常,您會創建一個自定義設置類來讀取這些值,如本文所述。就個人而言,我只會使用上面建議的 appSettings,因為這是現有的功能,而且表面上你所做的事情似乎已經足夠了。

但是,在不了解您的情況的情況下,如果沒有像這樣的自定義設置,您的嘗試可以解決:

在後面的程式碼中,我創建了一個受保護的函式來檢索設置

protected string GetCustomSetting(string Section, string Setting)
{
   var config = ConfigurationManager.GetSection(Section);

   if (config != null)
       return ((ClientSettingsSection)config).Settings.Get(Setting).Value.ValueXml.InnerText;

   return string.Empty;
}

然後在 aspx 標記中我呼叫這個函式

&lt;div&gt;
   &lt;label runat="server" id="label"&gt;&lt;%=GetCustomSetting("applicationSettings/MyApp.Properties.Settings", "ImagesUrl") %&gt;&lt;/label&gt;
&lt;/div&gt;

希望這可以幫助。

跟進:

CodeExpression 看起來像這樣:

public override CodeExpression GetCodeExpression(BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context)
{
   var config = ConfigurationManager.GetSection("applicationSettings/MyApp.Properties.Settings");
   return new CodePrimitiveExpression(((ClientSettingsSection)config).Settings.Get(entry.Expression).Value.ValueXml.InnerText);
}

在我的測試中,我創建了一個名為的類CustomSettingsExpressionBuilder並將其添加到 App_Code 文件夾中。將自定義 express 的配置添加到 web.config 並從 aspx 呼叫它,如下所示:

&lt;asp:Label ID="Label1" runat="server" Text="&lt;%$CustomSettings:ImagesUrl %&gt;"&gt;&lt;/asp:Label&gt;

引用自:https://stackoverflow.com/questions/6073914