我在一个asp.net mvc站点上遇到了问题。似乎“注销”部分不能正常工作。我可以登录,没有问题,但是当我注销时,我的代码抛出一个错误,而不是重定向到登录页面。我正在使用来自VisualStudio的“起始页面”。
我的web.config:
<authentication mode="Forms">
<forms
name="MyCookie"
loginUrl="~/Account/LogOn"
protection="All"
slidingExpiration="false"
path="/"
timeout="1"/>
</authentication> 登录函数:
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (Membership.ValidateUser(model.UserName, model.Password))
{
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}我有一个循环,每三秒。使用ajax调用函数,当我注销时(在1分钟后。正如在web.config中配置的一样),我得到了一个错误,而不是登录页面。
使用ajax调用的函数
[ActionName("StudentHelp")]
[Authorize]
[OutputCache(Duration = 3, VaryByParam = "none")]
public ActionResult StudentHelp()
{
var teacher = Membership.GetUser();
using(var db = new DbEntities())
{
var studentUserIds = (from p in db.Help
where p.TeacherId == (Guid) teacher.ProviderUserKey
&& p.IsHelped == false
select p).ToList();
IList<StudentModel> students = studentUserIds.Select(studentUserId => new StudentModel(studentUserId.StudentId)).ToList();
return PartialView("_StudentHelp", students);
}
}有什么线索吗?
thx /Mike
发布于 2012-05-02 15:46:21
您得到一个错误而不是登录页面的原因是因为您没有用[Authorize]属性修饰您的StudentHelp操作,这意味着该操作可以被未经验证的用户调用。除了在此操作中,您正在尝试获取当前登录的用户(Membership.GetUser()),当没有登录的用户(因为他的身份验证cookie已过期)时,它将返回null。然后在您的LINQ查询中使用teacher.ProviderUserKey,但是由于teacher变量为null,因此您将得到一个NullReferenceException。
更新:
由于存在known issue,您可能需要在web.config中添加以下密钥:
<appSettings>
<add key="loginUrl" value="~/Account/LogOn" />
<appSettings>发布说明还建议添加以下内容,但到目前为止,当我测试它时,这对我来说还不起作用:
<add key="autoFormsAuthentication" value="false" />https://stackoverflow.com/questions/10409506
复制相似问题