为什么Application_AuthenticateRequest被触发两次?

时间:2017-07-04 11:05:34

标签: asp.net model-view-controller login

我创造了一个'#34; hello world" MVC网站。我发现在"登录"单击按钮,我的代码重定向到" / Login / Index",Application_AuthenticateRequest在返回视图之前被触发一次,然后在返回视图后再次触发。为什么要解雇两次?

的LoginController:

    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Index(string user, string password)
    {
        if (user == "frank" && password == "pass")
        {
            Security.Login(Response, user, 10, "Doctor,Nurse");

            if (Request.IsAuthenticated)
                return View();
            else
                return RedirectToAction("Index");
        }
        else
        {
            return View();
        }
    }

查看:

<h2>Login Page</h2>

<br />

@if (Request.IsAuthenticated)
{
    <h3>User logged in as @User.Identity.Name.</h3>
}
else
{
    <h3>User <span style="color:red;font-weight:bold">not</span> logged in.</h3>
}

<br />

<form action="/Login/Index" method="post">
    User: <input type="text" name="user" value="frank"/>
    Password: <input type="text" name="password" value="pass" />
    <input type="submit" value="Login" />
</form>

的Global.asax:

    protected void Application_AuthenticateRequest(Object sender, EventArgs e)
    {
        HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];

        if (authCookie != null)
        {
            FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
            string[] roles = authTicket.UserData.Split(new Char[] { ',' });
            GenericPrincipal userPrincipal = new GenericPrincipal(new GenericIdentity(authTicket.Name), roles);
            Context.User = userPrincipal;
        }
    }

0 个答案:

没有答案