【发布时间】:2016-08-22 11:48:03
【问题描述】:
我想在 global.asax 和我的控制器之间建立连接。我们在我们的网站上使用了一个数据库。我们有一个代码来检查数据库是否存在。如果它不存在,我们想显示一条消息,如“数据库初始化”等。
GLOBAL.ASAX中的数据库检查:
public class MvcApplication : System.Web.HttpApplication
{
public static bool flag;
protected void Application_Start()
{
Database.SetInitializer<PhoneDexContext>(null);
var connString = ConfigurationManager.ConnectionStrings["DatabaseConnection"].ConnectionString;
using (PhoneDexContext db = new PhoneDexContext())
{
if (!db.Database.Exists())
{
flag = true;
db.Database.CreateIfNotExists();
}
}
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
protected void Application_BeginRequest()
{
if (flag)
{
Response.Redirect("Loading/LoadingScreen");
}
}
}
但是我们在使用响应重定向时遇到了问题。它返回
{“响应在此上下文中不可用。”}.
我们有一个控制器,它是 LoadingController,它有这个代码;
public class LoadingController : Controller
{
// GET: Loading
public ActionResult LoadingScreen()
{
return View();
}
}
但是我们不能跳到这部分。我怎样才能建立连接?谢谢
【问题讨论】:
-
你在哪里执行这个数据库检查代码? MVC 请求管道的哪一部分?
-
在 global.asax 中。我们不知道请求管道
-
请求和响应在启动时不可用。创建一个动作过滤器并让它进行数据库检查,然后根据需要重定向
-
您可以将 Session 值设置为 false,然后在 Home 控制器上检查,默认方法
-
嗯,但如果数据库未准备好,我想向用户显示警报,等待加载。我该怎么做?我想我应该在全球 asax 做
标签: c# asp.net-mvc asp.net-mvc-4