2014-02-26 101 views
0

我一直在將一些字符串值移動到我的web配置中,但是,在三元運算符中用作條件時,一個值返回null。AppSettings的值在三元運算符中返回空值

Web配置:

<add key="Main.Root" value="www.blah.com" /> 

AppSettings.cs:

public struct SiteRoots 
{ 
    public static readonly string Test = ConfigurationManager.AppSettings["Main.Root"]; 
} 

代碼:

ViewBag.Profile = HttpContext.IsDebuggingEnabled || HttpContext.Request.Url.Host == AppSettings.SiteRoots.Test ? AppSettings.GTMKeys.Test : AppSettings.GTMKeys.Live; 

如果我使用 「AppSettings.SiteRoots.Test」 其他地方的頁面上,它返回正確的值,它似乎只在三元運算符內用作條件時返回null。

+0

。 – Dirk

回答

1

括在paraenthesis的ternary表達,也確保AppSettings.GTMKeys.TestAppSettings.GTMKeys.Live給出boolean到,它可以與||使用。

ViewBag.Profile = HttpContext.IsDebuggingEnabled || (HttpContext.Request.Url.Host == AppSettings.SiteRoots.Test ? AppSettings.GTMKeys.Test : AppSettings.GTMKeys.Live); 

你可能如果你認爲三元運算符,然後只需將它轉換成if-else語句,看看它是否會消失的問題不需要HttpContext.IsDebuggingEnabled在表達

ViewBag.Profile = HttpContext.Request.Url.Host == AppSettings.SiteRoots.Test ? AppSettings.GTMKeys.Test : AppSettings.GTMKeys.Live; 
+1

他的意圖不是'ViewBag.Profile =(...)嗎?測試:現場? – Dirk

+0

是的,我同意你的意見,謝謝指點。 – Adil