簡體   English   中英

沒有使用ajax調用重定向到登錄頁面

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM