我正在制作一个ASP.Net MVC3应用程序。我现在使用Visual Studio 2010项目附带的内置验证代码。问题是我需要在登录后立即检索登录用户的数据库ID。我现在通过向账户控制器的登录操作添加代码,通过用户名查找数据库来从数据库中检索ID 。这适用于新登录,但不适用于“已记住”的登录。在重新启动应用程序时,最后一个用户会自动再次登录,但登录代码不会被触发,所以我没有得到数据库ID。如何进入自动重复登录?
我该如何解决这个问题?
编辑: 我试图实现丹尼尔的解决方案,看起来很有前途,我想出了这个代码。它nevers被称为虽然!我哪里错了?
的Global.asax.cs:
protected void Application_Start()
{
Database.SetInitializer<StandInContext>(new StandInInitializer());
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
this.AuthenticateRequest +=
new EventHandler(MvcApplication_AuthenticateRequest);
}
void MvcApplication_AuthenticateRequest(object sender, EventArgs e)
{
if(Request.IsAuthenticated)
{
using (var db = new StandInContext())
{
var authenticatedUser = db.AuthenticatedUsers.SingleOrDefault(
user => user.Username == User.Identity.Name);
if (authenticatedUser == null)
return;
var person = db.Persons.Find(authenticatedUser.PersonID);
if (person == null)
return;
Context.User = new CustomPrincipal(
User.Identity, new string[] { "user" })
{
Fullname = person.FullName,
PersonID = person.PersonID,
};
}
}
}
Dabblernl,那签名似乎不正确。尝试用'Application_AuthenticateRequest'替换'MvcApplication_AuthenticateRequest'并查看事件是否触发。 –
@丹尼尔卢齐:谢谢,它现在有效。我只是不明白'Application_AuthenticateRequest'方法如何在不被注册为EventHandler或作为覆盖的情况下突然被调用。 – Dabblernl
这就是AutoEventWireUp的魔力。这基本上可以节省你必须手动附加事件处理程序,如果你坚持方法命名的某种约定。看到[这个答案](http://stackoverflow.com/questions/4677866/global-asax-postauthenticaterequest-binding/4677905#4677905)一些更多的信息。 –