5

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 :-)

4
  • U can use a static class as U did in your global.asax. But it's not recommanded. Because it's hard to test using unit test. The proper way is to use dependencies injection as you did in your samples Commented Jul 31, 2017 at 13:52
  • What about a Service that returns you the connection string and color and inject it in every controller, you dont need to inject it in view, but send it to view as data. Commented Aug 1, 2017 at 15:38
  • I was hoping to avoid this, the project has multiple controllers, therefore repeated code to effectively do the same thing and I've already demonstrated in my code the Controller approach, but thank you. Commented Aug 1, 2017 at 16:14
  • Related post - Migrating global.asax to ASP.NET 5 Commented Oct 11, 2021 at 5:32

1 Answer 1

6

With a little more persistence and research I figured how to migrate my previous MVC5 Global.asax to ASP.NET Core Startup.cs. Below you will see all associated code to achieve Host determined AppSettings.

appsettings.json

{
  "ConnectionStrings": {
    "External": "Data Source=externalserver;Initial Catalog=externaldatabase;Persist Security Info=True;User ID=externalid;Password=externalpassword",
    "Internal": "Data Source=internalserver;Initial Catalog=internaldatabase;Persist Security Info=True;User ID=internalid;Password=internalpassword",
    "Test": "Data Source=testserver;Initial Catalog=testdatabase;Persist Security Info=True;User ID=testid;Password=testpassword"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
}

AppSettings.cs

namespace WebApplication1
{
    public class AppSettings
    {
        public string Colour;

        public string ConnectionString;
    }
}

Startup.cs

using System;
using System.Net;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace WebApplication1
{
    public class Startup
    {
        public AppSettings AppSettings;

        public static string Colour;

        public static string External;

        public static string HostName;    

        public static string Internal;

        public static string Test;

        public Startup(IHostingEnvironment hostingEnvironment)
        {
            var configurationBuilder = new ConfigurationBuilder().SetBasePath(hostingEnvironment.ContentRootPath).AddJsonFile("appsettings.json", true, true).AddJsonFile($"appsettings.{hostingEnvironment.EnvironmentName}.json", true).AddEnvironmentVariables();

            Configuration = configurationBuilder.Build();                

            External = Configuration.GetConnectionString("External");

            Internal = Configuration.GetConnectionString("Internal");                

            Test = Configuration.GetConnectionString("Test");
        }

        public IConfigurationRoot Configuration { get; }

        public void ConfigureServices(IServiceCollection serviceCollection)
        {
            serviceCollection.AddMvc();

            serviceCollection.Configure<AppSettings>(appSettings =>
            {
                HostName = Dns.GetHostName().ToLower();

                switch (HostName)
                {
                    case "external-domain":
                        appSettings.ConnectionString = External;                                                        
                        appSettings.Colour = "blue";
                        
                        break;
                    case "internal-domain":
                        appSettings.ConnectionString = Internal;                            
                        appSettings.Colour = "purple";                            
                        break;
                    default:                              
                        appSettings.ConnectionString = Test;                            
                        appSettings.Colour = "red";                            
                        break;
                }
            });
        }
        
        public void Configure(IApplicationBuilder applicationBuilder, IHostingEnvironment hostingEnvironment, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (hostingEnvironment.IsDevelopment())
            {
                applicationBuilder.UseDeveloperExceptionPage();
                applicationBuilder.UseBrowserLink();
            }
            else {
                applicationBuilder.UseExceptionHandler("/Home/Error");
            }

            applicationBuilder.UseStaticFiles();

            applicationBuilder.UseMvc(routes =>
            {
                routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

HomeController.cs

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;

namespace WebApplication1.Controllers
{
    public class HomeController : Controller
    {
        private readonly AppSettings _appSettings;

        public HomeController(IOptions<AppSettings> appSettings)
        {
            _appSettings = appSettings.Value;
        }

        public IActionResult Index()
        {
            var colour = _appSettings.Colour;

            return View();
        }

        public IActionResult Error()
        {
            return View();
        }
    }
}

Within a view, you can use Dependency Injection like so:

@using Microsoft.Extensions.Options
@{
    @inject IOptions<AppSettings> OptionsAppSettings

    @OptionsAppSettings.Value.Colour;
}

I hope this proves useful to others :-)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.