Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC Post for @Url.action()

I have the following controller auto-generated by asp.net

    //
    // POST: /Account/LogOff
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult LogOff()
    {
        AuthenticationManager.SignOut();
        return RedirectToAction("Index", "Home");
    }

Now I have a log off button. Currently it looks like this:

   <div class="userdrop">
                <ul>
                    <li><a href="@Url.Action("Manage", "Account")">Profile</a></li>                       
                    <li><a href="@Url.Action("LogOff", "Account")">Logout</a></li>
                </ul>
            </div><!--userdrop-->

But it does not work and I am guessing it is cause it is a Post action method.

How would I go about "logging off" ?

[EDIT]

Why is it auto-generated as an Http Post? Is it more secure that way? Does it not send the cookie with it when it logs out?

like image 769
Zapnologica Avatar asked Jan 28 '14 13:01

Zapnologica


2 Answers

How would I go about "logging off" ?

By using a form instead of an anchor:

<li>
    @using (Html.BeginForm("LogOff", "Account"))
    {
        @Html.AntiForgeryToken()
        <button type="submit">Logout</button>
    }
</li>

You could call the CSS wizards to style this button look like an anchor if you want. But the semantically correct element in this case is an html form which allows you to send a POST verb.

like image 67
Darin Dimitrov Avatar answered Sep 26 '22 13:09

Darin Dimitrov


There is no compelling reason for this to be an HttpPost. I know it's generated that way, but you're not actually POSTing any data. Just remove the attribute and it will work as is.

Now, if you want it to work with the HttpPost then you'll need to wrap this in a Form and make it a submit button or submit the form onclick.

<li>
    @using (Html.BeginForm("LogOff", "Account",
        FormMethod.Post, new { id = "LogOffForm" }))
    {
        @Html.AntiForgeryToken()
        <a href="@Url.Action("LogOff", "Account")"
            onclick="$('#LogOffForm').submit();">Logout</a>
    }
</li>
like image 29
Mike Perrenoud Avatar answered Sep 24 '22 13:09

Mike Perrenoud