如何将C#MVC5 Global.asax迁移到ASP.NET Core Startup.cs

时间:2017-07-31 13:44:48

标签: c# asp.net-core asp.net-mvc-5

有人可以演示如何成功声明ASP.NET Core中依赖主机名的静态项目变量吗?

以前我的代码类似于下面的代码,使用Global.asax来识别运行项目的主机名,并设置整个项目可以使用的一些简单静态变量,如'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;
    }
}

我已经看到了将AppSetting传递给HomeController的示例,例如:

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();
    }
}

还看到了注入的例子,直接在ASP.NET核心MVC应用程序中的Razor视图中使用AppSettings,如下所示:

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

    @OptionsAppSettings.Value.Colour;
}

是否有更简单的方法类似于Global.asax而无需在每个Controller或每个View中重新声明?

我遇到困难的最大工作是如何在Startup.cs中获取主机名,它似乎只能在事件发生后才可用,也许在控制器级别之前可以获取并设置这些变量。

非常感谢任何帮助: - )

1 个答案:

答案 0 :(得分:0)

通过更多的持久性和研究,我想到了如何将我以前的MVC5 Global.asax迁移到ASP.NET Core Startup.cs。下面您将看到实现主机确定的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();
        }
    }
}

在视图中,您可以像这样使用依赖注入:

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

    @OptionsAppSettings.Value.Colour;
}

我希望这对其他人有用: - )