简体   繁体   中英

AppSettings value is returning null in ternary operator

I've been moving some of my string values into my web config, however, one value is returning null when used as a condition in a ternary operator.

Web Config:

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

AppSettings.cs:

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

Code:

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

If I use "AppSettings.SiteRoots.Test" anywhere else on the page, it returns the correct value, it only seems to return null when used as a condition inside the ternary operator.

Enclose the ternary expression in paraenthesis, also ensure AppSettings.GTMKeys.Test and AppSettings.GTMKeys.Live gives boolean to that it could be used with || .

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

You probably do not need HttpContext.IsDebuggingEnabled in your expression

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM