首页 > 解决方案 > Asp.net MVC 5 视图在使用 F5 重新加载页面之前不呈现

问题描述

当我的应用程序的用户直接按下“注销”按钮时,他们将被注销并返回到登录页面(有关这两个操作,请参见下面的代码)。这按预期工作,但是管理员用户可以强制注销单个用户。我目前正在使用 SignalR 完成此操作,并且遇到了一个奇怪的问题。

当我从客户端方法重定向到LogOff时,一切都被正确调用。客户端用户已注销,并RedirectToAction正确重定向到LogIn操作。但是,在LogIn我使用 F5 手动刷新页面之前,视图不会呈现。我完全无法弄清楚为什么视图没有第一次呈现

注销操作

    public ActionResult LogOff()
    {
        FormsAuthentication.SignOut();

        return RedirectToAction("Login", "Account");
    }

登录操作

    public ActionResult Login(string returnUrl, string displayMsg)
    {
        ViewBag.ReturnUrl = returnUrl;
        ViewBag.DisplayMsg = displayMsg;
        ViewBag.PasswordAttempts = 0;
        return View();
    }

SignalR 客户端方法

$.connection.hub.start();
authHub.client.LogOut = function () {
    $.ajax({
        url: '@Url.Action("LogOff", "Account", new { area = ""})',
        type: "POST"
    });
    $.connection.hub.stop();
}

登录查看

section id="loginForm">

            <div class="col-md-12">
                <div class="wrap">
                    <p class="form-title">Log In</p>

                        @using (Html.BeginForm("Login","Account",new {ViewBag.ReturnUrl, ViewBag.PasswordAttempts}, FormMethod.Post, new{@class="login"}))
                        {
                            @Html.AntiForgeryToken()
                            <section class="DisplayMsg">@ViewBag.DisplayMsg</section>

                            <section>@Html.ValidationMessageFor(m => m.UserName) </section>
                            <label>User Name:</label> @Html.TextBoxFor(m => m.UserName)

                            <section>@Html.ValidationMessageFor(m => m.Password)</section>
                            <label>Password:</label>@Html.PasswordFor(m => m.Password)

                            <input type="submit" value="Log In" class="btn btn-success btn-sm" />
                                @*<div class="reset-forgot">
                                    <div class="row">
                                        <div class="col-md-6 reset-pass-content">
                                            @Html.ActionLink("Reset Password", "PasswordReset", "Account", new {area = string.Empty})
                                        </div>
                                    </div>
                                </div>*@
                        }
                </div>
            </div>

标签: javascriptc#jqueryasp.net-mvc-5signalr

解决方案


因为你做了一个 Ajax 调用,它永远不会将用户重定向到登录页面,它只会在服务器端注销用户。在服务器中注销后,您可以使用location.href将用户重定向到登录页面:

$.connection.hub.start();
   authHub.client.LogOut = function () {
      $.connection.hub.stop();
      $.ajax({
      url: '@Url.Action("LogOff", "Account", new { area = ""})',
      type: "POST",
      success: function(){
          location.href = '@Url.Action("Login", "Account")'
      }
  });
}

推荐阅读