0

I have this link in Home.cshtml (This has an ActionResult of public ActionResult Home())

<li class="home-links home-middleLast">@Html.ActionLink("Log out", "LogOut", "Home")</li>

It is suppose to link to this controller

// /LogOut
public ActionResult LogOut()
{
    FormsAuthentication.SignOut();
    TempData.Clear();
    Session.Abandon();
    getDB.Close();
    return RedirectToAction("Home");
}

I made this happen using this

[Route("~/log_out")]

and this

routes.MapMvcAttributeRoutes();

My concern is that someone could type in /log_out into the url and it would log out of the account. How can I make it so that people won't do that?

I want to make it so you have to click the link to log out instead of typing in /log_out into the url.

3 Answers3

0

i think this is a dumb way.. but you can try this

<li class="home-links home-middleLast"><form action="@Url.Action("LogOut","Home")" method="post"><button type="submit">Log Out</button></form></li>

and add [HttpPost] above your action

//LogOut
[HttpPost]
public ActionResult LogOut()
{
    FormsAuthentication.SignOut();
    TempData.Clear();
    Session.Abandon();
    getDB.Close();
    return RedirectToAction("Home");
}

but... you must change Log Out button and style it so it looks like a link with css

Anggra
  • 1
0

This needs script:

@Html.ActionLink("Log out", "LogOut", "Home", null, new { @class= "logout-btn" })

<script>
    $(function () {
        $(".logout-btn").click(function (e) {
            e.preventDefault();
            var url = $(this).attr("href");
            $.ajax({
                url: url,
                success: function (data) {
                    if (data) {
                        // change to your location
                        window.location.href = "http://stackoverflow.com";
                    }
                }
            });
        });
    });
</script>

and the Action:

public ActionResult LogOut()
{
    if (Request.IsAjaxRequest())
    {
        FormsAuthentication.SignOut();
        TempData.Clear();
        Session.Abandon();
        getDB.Close();
        return Json(true, JsonRequestBehavior.AllowGet);
    }

    return Json("Invalid request", JsonRequestBehavior.AllowGet);
}
RickL
  • 3,318
  • 10
  • 38
  • 39
0

View

using (Html.BeginForm("LogOut", "Home", FormMethod.Post))
{
    <li class="home-links home-middleLast"><input type="submit" value="Log out"/></li>
}

Controller

[HttpPost]
[Route("")]
[Route("~/home")]
public ActionResult LogOut()
{
    FormsAuthentication.SignOut();
    TempData.Clear();
    Session.Abandon();
    getDB.Close();
    return RedirectToAction("Home");
}

I put the home route on the LogOut Controller as well is HttpPost. This will only hit when the button is pressed.

EDIT: I didn't use the previous answer I submitted. I actually used this https://stackoverflow.com/a/14194770/6804700