简体   繁体   中英

Ajax Post not recognizing my AntiForgeryToken

I'm trying to do an $.ajax post with this code:

$('button#removeTeamMember').click(function() {
        var thisPlayerId = $(this).attr('data-bind').valueOf();
        var thisTeamId = $('#hidden').text();
    alert("PlayerId: " + thisPlayerId + " TeamId: " + thisTeamId);

    $.ajax({
        type: "POST",
        url: "/Teams/RemoveTeamMember",
        data: AddAntiForgeryToken({ playerId: thisPlayerId, teamId: thisTeamId }),
        dataType: "text",
        contentType: "application/json",
        success: function(returnedData) {
            if (returnedData.success === true) {
                window.location = "/Teams/Details?id=" + thisTeamId;
            } else {
                alert("An error occurred removing the team member.");
            }
        },
        error: function(jqxhr, textStatus, errorThrown) {
            alert("jqxhr: " + jqxhr.readyState + "; " + jqxhr.status + "; " + jqxhr.responseText);
            alert("textStatus: " + textStatus);
            alert("errorThrown: " + errorThrown);
        },
        async: false
    });
});

And here's my controller code:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult RemoveTeamMember(int playerId, int teamId)
{
    var teamMember = _teamMemberRepository.Query().FirstOrDefault(tm => tm.Player.PlayerId == playerId && tm.Team.TeamId == teamId);
    _teamMemberRepository.Delete(teamMember);

    //return RedirectToAction("Details");
    return Json(new {success = true});
}

Here's the view code:

<form method="POST" action="#" role="form">
        @Html.AntiForgeryToken()

        <div class="panel panel-primary">
            <div class="panel-heading"><h3>@Model.Team.TeamName</h3></div>
            <div class="panel-body">
                <div class="col-md-6">
                    <table class="table table-striped">
                        <thead>
                            <tr>
                                <th>Player Type</th>
                                <th>Player</th>
                                <th>Handicap</th>
                                <th></th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>Manager</td>
                                <td>@Html.ActionLink(@Model.Team.TeamManager.DisplayName, "#")</td>
                                <td></td>
                                <td></td>
                            </tr>

                            @foreach (var teamMember in @Model.Team.TeamMembers)
                            {
                                <tr>
                                    <td>Player</td>
                                    <td><a href="#">@teamMember.Player.DisplayName</a></td>
                                    <td>Handicap</td>
                                    <td>
                                        <button id="removeTeamMember" class="btn btn-xs btn-danger" data-bind="@teamMember.Player.PlayerId">Remove</button>
                                        <div id="hidden" style="visibility: hidden">@teamMember.Team.TeamId</div>
                                    </td>
                                </tr>
                            }
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </form>

I'm getting the error back saying the AntiForgeryToken is not present, even though it's getting called via the "AddAntiForgeryToken" which I got from here . What else am I doing wrong?

Ensure that you have added the anti forgery to view.

You must have the following in current razor page.

@Html.AntiForgeryToken()

This will render the correct html token into the page, AddAntiForgeryToken will select this element and insert it into your ajax data.

The AddAntiForgeryToken function from the answer you linked assumes that your AntiForgeryToken hidden field input has a container (the form) with this id: __AjaxAntiForgeryForm . You don't have that. Either remove the id from the selector and replace it with form for example:

$('form input[name=__RequestVerificationToken]').val();

Or add the id to the form:

<form method="POST" action="#" role="form" id="__AjaxAntiForgeryForm">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM