MVC3 Razor Engine执行/渲染顺序 [英] MVC3 Razor Engine execution/rendering order

查看:87
本文介绍了MVC3 Razor Engine执行/渲染顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在_layout模板中有一些链接(登录,注销和注册),这些链接的显示取决于用户是否登录.

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();
}

我已经通过此链接- http://mvcdev.com/differences-between-asp-net-razor-and-web-forms-view-engines/-解释了Razor引擎的执行顺序,但在我看来,执行方式有所不同.理想情况下,我希望FormsAuthentication.SignOut()在_layout中的User.Identity.IsAuthenticated之前执行.

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 my case it seems to be executing differently. Ideally I would expect the FormsAuthentication.SignOut() to execute before the User.Identity.IsAuthenticated in the _layout.

我做错了什么?谢谢!

推荐答案

这很正常,您需要在注销后进行重定向:

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

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

    return RedirectToAction("Index");
}

发生这种情况的原因是,当客户端请求注销链接时,他仍处于身份验证状态(他与请求一起发送了身份验证cookie).然后,在控制器操作中,您将其注销(FormsAuthentication.SignOut()),该操作仅标记了身份验证cookie以在后续请求中将其删除.然后,您返回一个视图,并且在该视图内,用户当然仍会通过身份验证,因为该视图在相同的请求下执行,并且cookie仍然存在.

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.

这篇关于MVC3 Razor Engine执行/渲染顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆