Could somebody please demonstrate how to successfully declare static project variables that are Host Name dependant in ASP.NET Core?
Previously I had code similar to that featured below, to use the Global.asax to identify the Host Name from which the project was running and to set some simple static variables that the entire project could use like so 'MvcApplication.Colour'
public static string Colour;
public static string ConnectionString;
public static string HostName = System.Web.Hosting.HostingEnvironment.ApplicationHost.GetSiteName().ToLower();
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
ProjectSettings();
}
public static void ProjectSettings()
{
switch (HostName)
{
case "external-domain":
ConnectionString = WebConfigurationManager.ConnectionStrings["External"].ToString();
Colour = "blue";
break;
case "internal-domain":
ConnectionString = WebConfigurationManager.ConnectionStrings["Internal"].ToString();
Colour = "purple";
break;
default:
ConnectionString = WebConfigurationManager.ConnectionStrings["Test"].ToString();
Colour = "red";
break;
}
}
I have seen examples of passing the AppSetting to the HomeController such as:
public class HomeController : Controller
{
private readonly Startup.AppSettings _appSettings;
public HomeController(IOptions<Startup.AppSettings> appSettings)
{
_appSettings = appSettings.Value;
}
public IActionResult Index()
{
var colour = _appSettings.Colour;
return View();
}
public IActionResult Error()
{
return View();
}
}
Also seen examples of injection, directly using AppSettings in Razor Views within an ASP.NET Core MVC application like so:
@using Microsoft.Extensions.Options
@{
@inject IOptions<Startup.AppSettings> OptionsAppSettings
@OptionsAppSettings.Value.Colour;
}
Is there any easier way similar to Global.asax without having to re-declare within each Controller or each View?
The greatest job I'm having difficulty with, is how to obtain the Host Name within the Startup.cs, it seems its only available after the event, maybe there is away to obtain and set these variables prior to Controller level.
Any help would be much appreciated :-)