在ASP中使用全局变量.净MVC
本文关键字:全局变量 MVC ASP | 更新日期: 2023-09-27 18:17:54
首先看一下示例控制器代码。你会发现有两条语句是重复的——
public class DashboardController : Controller
{
//the following line is repetitive for every controller.
String ConnectionString = WebConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
public ActionResult Index()
{
try
{
//codes
}
catch (Exception Ex)
{
//The following line is repetitive for every action method.
var path = HttpContext.Server.MapPath("~/App_Data");
ExceptionLog.Create(Ex, path);
}
return View("AdminDashboard");
}
}
我希望避免这样的重复。有没有办法做到这一点,可以为整个应用程序作为全局变量工作?
如果是我,我需要访问频繁的配置选项,我会创建/公开某种IAppConfiguration
,我可以将其放入我的控制器中(使用依赖注入)。比如:
public interface IAppConfguration
{
String MyConnectionString { get; }
String ServerPath { get; }
}
public class AppConfiguration : IAppConfiguration
{
private readonly HttpContext context;
public AppConfiguration(HttpContext context)
{
this.context = context;
}
public String MyConnectionString
{
get { return COnfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
}
public String ServerPath
{
get { return context.Server.MapPath("~/"); }
}
}
然后您可以将其扩展到不同的情况,子站点/区域等。然后,通过控制器的构造函数引入它:
public class MyController : Controller
{
private readonly IAppConfiguration config;
public MyController()
: this(new AppConfiguration(HttpContext.Current))
{
}
public MyController(IAppConfiguration config)
{
this.config = config;
}
// reference config.ServerPath or config.MyConnectionString;
}
更进一步,您可以在此基础上添加一个工厂,将其作为参考,并允许您获得其他环境的配置设置。例如
IAppConfiguration config = configFactory.GetConfig(/* environment */);
我喜欢这种方法的地方是允许我替换本地[单元/集成]测试的设置。使用基本控制器/静态类会使以后替换这些值变得非常困难。
下面是一个使用基本控制器方法的示例:
public abstract class BaseController : Controller
{
protected string ConnectionString = WebConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
protected void LogException(Exception ex)
{
var path = HttpContext.Server.MapPath("~/App_Data");
ExceptionLog.Create(Ex, path);
}
}
public class DashboardController : BaseController
{
public ActionResult Index()
{
try
{
string conn = base.ConnectionString;
//codes
}
catch (Exception ex)
{
base.LogException(ex);
}
return View("AdminDashboard");
}
}
为了避免异常捕获,您可以在global.asax.cs:
的OnError
事件处理程序中记录它。protected void Application_Error(object sender, EventArgs e)
{
HttpContext ctx = HttpContext.Current;
Exception ex = ctx.Server.GetLastError();
var path = HttpContext.Server.MapPath("~/App_Data");
ExceptionLog.Create(Ex, path);
}
你可以使用连接字符串名称"MyConnectionString"代替WebConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString
时,传递给dbcontext或ADO连接。
但更合理的方式是注入(与依赖注入)在控制器类,将负责与数据库的工作,而不是创建它在控制器和传递那里的连接字符串。
您可以继承控制器,然后将其用于所有其他控制器,看看类似的问题,我如何继承ASP。. NET MVC控制器,只改变视图?
但是这只能在控制器中访问,你也可以创建一个带有静态方法或属性的类,返回连接字符串。可以在任何可以访问该类的代码路径中使用。