0

I have a jquery function:

function ExpireSession() {
            $.ajax({
                type: "POST",
                url: '@Url.Action("LogOffSession","Account")',
                dataType: "json",
                success: function (data) {
                },
                error: function (data) {
                }
            });
        }

The action method that is called from the above function is:

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult LogOffSession()
    {
        Session.Abandon();
        FormsAuthentication.SignOut();
        return Json(new { result = true });
    }

The jquery function is called(i tested with an alert) but the action method is not being called. I tried giving something in success and error functions but no effect.

I also tried by giving the jquery function like this

function ExpireSession() {
            var url = '@Url.Action("LogOffSession", "Account")';
            $.post(url, null, function (data) {
                return true;
            });

but still it is not working.

What is that I am doing wrong?

nitinvertigo
  • 1,180
  • 4
  • 32
  • 56
  • 6
    Your method is decorated with `[ValidateAntiForgeryToken]` but your not passing the token so the method will never run. –  Oct 09 '15 at 08:09
  • @StephenMuecke is correct. You can diagnose issues like this by checking the result of the request in the console. In this instance you would most likely have seen a 500 error. – Rory McCrossan Oct 09 '15 at 08:10
  • Yes you are right. Removing the ValidateAntiForgeryToken from the action method does the job... – nitinvertigo Oct 09 '15 at 08:26

2 Answers2

0

The reason the method was failing was the inclusion of AntiForgeryToken on the action method. Removing it does the trick.

To include the AntiForgeryToken in your action method and your jquery call, check this out.

Thanks to Stephen Muecke for the clarification.

Community
  • 1
  • 1
nitinvertigo
  • 1,180
  • 4
  • 32
  • 56
0

You could try to do it like the default MVC template, include a form in your page like this:

@if (Request.IsAuthenticated)
            {
                using (Html.BeginForm(MVC.Account.LogOff(), FormMethod.Post, new { id = "logoutForm" }))
                {
                    @Html.AntiForgeryToken()

                    <a href="javascript:document.getElementById('logoutForm').submit()">
                        <i class="fa fa-sign-out"></i> Log out
                    </a>
                }
            }

You can just do document.getElementById('logoutForm').submit() from javascript to logout. Don't need to include the logout link in the form, it can be hidden. This takes care of the AntiForgeryToken.
However I would argue, that you don't need to protect your logout method with AntiForgeryToken, you could remove the attribute and just call the url as you do now.

Attila Szasz
  • 3,033
  • 3
  • 25
  • 39