Search code examples
c#asp.netasp.net-mvc-5antiforgerytoken

AntiForgeryToken not submitting on form submission via href link


code snippet...

    <div class="row">
        <div class="col-md-4">
            @* test code *@
            <form action="/Account/LogOff/" id="logoutForm" class="logoutForm" method="post">
                @Html.AntiForgeryToken()
                @*<input type="submit" value="LogOff" />*@
                <a href="javascript:document.getElementById('logoutForm').submit()">@xx.Web.Resources.AccountLogin.Logout</a>
            </form>

            @* original code *@
            @*@using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "logoutForm" }))
            {
                @Html.AntiForgeryToken()

             <a href="javascript:document.getElementById('logoutForm').submit()">@xx.Web.Resources.AccountLogin.Logout</a>
            }*@
        </div>
    </div>
</code>

//*********   controller code

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



Confirming that the token has been generated and is in the page.

Pic to confirm, token is in the generated page.

so the "@* original code *@" is from a newly generated mvc5 application template. In a brand new app, it works great and your logged out.

In the app I'm building it has stopped working. The test code(above @* test code *@) I have works if I use an input button to submit the form. If I use the

Any ideas on what would prevent form fields from being submitted? thanks in advance.


Solution

  • So still don't understand what is going on here.

    However, the following fixes it.

    Changed "javascript:document.getElementById('logoutForm').submit()" to call a local js function which does the submitting.

    function SubmitMe() {
     $("<input />").attr("type", "hidden")
          .attr("name", "__RequestVerificationToken")
          .attr("value", $('input[name=__RequestVerificationToken]').val())
              .appendTo("#logoutForm");
    $("#logoutForm").submit();
    
    }