我刚刚开始学习 asp.net MVC3,我遇到了这个问题:
我正在使用 Visual Studio 2010,并且在构建过程中没有错误,只有当我尝试运行应用程序时。我正在谷歌上寻找答案,但没有成功。有谁知道如何解决这个问题?
谢谢!
EDIT-ContextModule 代码:
using System;
using System.Web;
namespace testbaza.Models
{
public class ContextModule : IHttpModule
{
internal const string CONTEXT_KEY = "datacontext";
public void Dispose()
{
}
public void Init(HttpApplication context)
{
context.PostRequestHandlerExecute += new EventHandler(context_PostRequestHandlerExecute);
context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute);
}
private void context_PreRequestHandlerExecute(object sender, EventArgs e)
{
if (HttpContext.Current.Session != null)
{
HttpContext.Current.Session[CONTEXT_KEY] = new EntitiesModel();
}
}
private void context_PostRequestHandlerExecute(object sender, EventArgs e)
{
CommitTransactions();
DisposeContext();
ClearSession();
}
private void CommitTransactions()
{
if (HttpContext.Current.Session == null)
{
return;
}
EntitiesModel dbContext =
HttpContext.Current.Session[CONTEXT_KEY] as EntitiesModel;
if (dbContext != null)
{
dbContext.SaveChanges();
}
}
private void DisposeContext()
{
if (HttpContext.Current.Session == null)
{
return;
}
EntitiesModel dbContext =
HttpContext.Current.Session[CONTEXT_KEY] as EntitiesModel;
if (dbContext != null)
{
dbContext.Dispose();
}
}
private void ClearSession()
{
if (HttpContext.Current.Session == null)
{
HttpContext.Current.Session.Remove(CONTEXT_KEY);
}
}
}
}