我遇到了asp.net mvc网站的问题。似乎“退出”部分无法正常工作。我可以登录,没问题,但是当我注销时,我的代码会抛出错误而不是重定向到登录页面。我正在使用VisualStudio的“starterpage”。
我的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);
}
我有一个每3秒一个循环。使用ajax调用函数,当我注销时(在web.config中配置1分钟后),我得到一个错误而不是登录页面。
使用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
答案 0 :(得分:0)
您收到错误而不是登录页面的原因是因为您没有使用[Authorize]
属性修饰StudentHelp
操作,这意味着未经身份验证的用户可以调用此操作。除了在此操作中,您尝试获取当前登录的用户(Membership.GetUser()
),当用户不再登录时将返回null(因为他的身份验证cookie已过期)。然后在您的LINQ查询中使用teacher.ProviderUserKey
,但由于teacher
变量为null,因此您获得NullReferenceException
。
更新:
由于known issue您可能需要将follownig密钥添加到您的web.config中:
<appSettings>
<add key="loginUrl" value="~/Account/LogOn" />
<appSettings>
发行说明还建议添加以下内容,但到目前为止,当我测试它时,这对我没有用处:
<add key="autoFormsAuthentication" value="false" />