开发者

MVC3 Razor Engine execution/rendering order

I have a few links (login, logout, and register) in the _layout template, where the links are shown depending on whether the user is logged in. Like so:

if (User.Identity.IsAuthenticated)
{
    <span class="username">@User.Identity.Name</span>
    <span class="link">@Html.ActionLink("Logout", "Logout", "Account")</span>
}
else
{
    <span class="link">@Html.ActionLink("Login", "Login", "Account")</span>
    <span class="link">@Html.ActionLink("Register", "Register", "Account")</span>
}

Problem is that the logout link is still displayed the first time the user logs out of the system (I would expect that to be immediately replaced with the login, and register links) - that is until the page is refreshed, or the user moves to another page. Here is the logout action code:

public ActionResult Logout()
{
    FormsAuthentication.SignOut();
    Session.Abandon();

    return View();
}

I have gone through this link - http://mvcdev.com/differences-between-asp-net-razor-and-web-forms-view-engines/ - which explains the execution order of the Razor engine, but in 开发者_如何学JAVAmy case it seems to be executing differently. Ideally I would expect the FormsAuthentication.SignOut() to execute before the User.Identity.IsAuthenticated in the _layout.

What am I doing wrong? Thanks!


That's normal, you need to redirect after logging out:

public ActionResult Logout()
{
    FormsAuthentication.SignOut();
    Session.Abandon();

    return RedirectToAction("Index");
}

The reason this happens is because when the client requested the Logout link he was still authenticated (he sent the authentication cookie along with the request). Then inside the controller action you are logging him out (FormsAuthentication.SignOut()) which does nothing more than mark the authentication cookie for removal on subsequent requests. Then you return a view, and inside this view of course the user is still authenticated as this view executes under the same request and the cookie is still present.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜