Fabián Rojas
Fabián Rojas

Reputation: 28

SignOut() in asp.net MVC 4

I have the following code to sign out and redirect to another page in the controller:

...
public ActionResult Logout(){
    FormsAuthentication.SignOut();
    return Redirect("Index");
}
...

I have the following "Master Page":

...
<body>
    <header>
        <div style="background-color:deepskyblue; width:100%; height:20px">
            @if(User.Identity.IsAuthenticated){
                <a style="position:relative; float:right; right:15px" href="@Url.Action("Logout", "Home", null)">Logout</a>
            }
            else{
                <a style="position: relative; float: right; right: 15px" href="@Url.Action("Login", "Home", null)">Login</a>
            }
        </div>
    </header>
    @RenderBody()
    <footer>
        <div style="position:relative; background-color:lightslategrey; width:100%; height:20px">
            @if(User.Identity.IsAuthenticated){
                <a style="position: relative; float: left; left: 15px" href="@Url.Action("Index", "Home", null)">Go back</a>
            }
        </div>
    </footer>
</body>
...

The problem is: when the Logout action is called, it redirects to de Index page, but the header and footer do not change, I have to click "Sign out" again or Refresh the page and then it works.

How can it work without having to click twice or refreshing the page?

Upvotes: 0

Views: 1947

Answers (2)

Fabi&#225;n Rojas
Fabi&#225;n Rojas

Reputation: 28

I fixed it changing this:

            @if(User.Identity.IsAuthenticated){
                 <a style="position:relative; float:right; right:15px" href="@Url.Action("Logout", "Home", null)">Logout</a>
            }
            else{
                 <a style="position: relative; float: right; right: 15px" href="@Url.Action("Login", "Home", null)">Login</a>
            }

with this:

            @if(User.Identity.IsAuthenticated){
                 @Html.ActionLink("Logout", "Logout", "MyAccount", null, new{@style="position:relative; float:right; right:15px"})
            }
            else{
                 @Html.ActionLink("Login", "Login", "MyAccount", null, new{@style="position: relative; float: right; right: 15px"})
            }

Thank you anyways for your answers.

Upvotes: 0

Ross Bush
Ross Bush

Reputation: 15155

Why are you using Redirect() here? RedirectToAction() is the preferred way to issue a 302 redirect within the context of your application. It adheres to your routing. I would thing that Redirect("Index") would not always work as Redirect("/Controller/Index") would.

return RedirectToAction("Controller", "Index");

Upvotes: 1

Related Questions