[英]No redirect to login page with ajax call
我在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);
}
我有一个循环,每三秒一次。 调用带有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 /迈克
出现错误而不是登录页面的原因是,您没有使用[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" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.