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