简体   繁体   English

反伪造令牌和Ajax JSON.stringify发布不起作用

[英]Anti Forgery Token and Ajax JSON.stringify Post Does not Work

I tried to use Anti Forgery token with JSON.stringify and i check many site but i failed to success.this is my ajax code that delete some info without any problem.now i add anti forgery token and i dont know how to change my ajax code to work fine.i also added ValidateAntiForgeryToken to my action. 我试图将防伪令牌与JSON.stringify一起使用,并且我检查了许多站点,但未成功。这是我的ajax代码,可以毫无问题地删除一些信息。现在我添加了防伪令牌并且我不知道如何更改我的ajax代码正常工作。我还向我的操作中添加了ValidateAntiForgeryToken。

<script src="../../Scripts/jquery-1.8.3.js"></script>
<script src="../../Scripts/jquery-ui-1.9.2.custom.js"></script>
    <script>
        $(function () {
            $(":checkbox").change(function () {
                var $this = $(this);
                if ($this.is(":checked")) {
                    $this.closest("tr").addClass("SlectedtRow");
                } else {
                    $this.closest("tr").removeClass("SlectedtRow");
                }
            })
            var tittle = '';
            var url = '';
            $("#dialog").dialog({
                autoOpen: false,
                width: 400,
                modal: true,
                resizable: false,
                buttons: [
                    {
                        text: "بلی",
                        click: function () {
                            Delete();
                            $(this).dialog("close");
                        }
                    },
                    {
                        text: "خیر",
                        click: function () {
                            $(this).dialog("close");
                        }
                    }
                ]
            });
            var IsActive
            // Link to open the dialog
            $(".insertBtn").click(function (event) {

                var IsSelected = false;
                var ModalText = "  آیا کاربر ";
                $('#userForm input:checked').each(function () {
                    ModalText += this.value + " - "
                    IsSelected = true;

                });

                if (IsSelected) {
                    document.getElementById('ErrorContent').style.display = "none";
                    ModalText = ModalText.slice(0, -2);
                    if (this.id == 'DeleteUser') {
                        ModalText += " حذف گردد  "
                        tittle = 'حذف کاربر'
                        url = '@Url.Action("DeleteUser", "UserManagement")';
                    }
                    else if (this.id == 'InActiveUser') {
                        ModalText += " غیر فعال گردد  "
                        tittle = 'تغییر فعالیت کاربر '
                        url = '@Url.Action("ChangeActiveStatus", "UserManagement")';
                    IsActive = false;
                }
                else if (this.id == 'ActiveUser') {
                    ModalText += "  فعال گردد  "
                    tittle = 'تغییر فعالیت کاربر '
                    url = '@Url.Action("ChangeActiveStatus", "UserManagement")';
                    IsActive = true;
                }
        $('#ModalMessgae').text(ModalText);


        $("#dialog").dialog("open");
        $("#ui-id-1").text(tittle);
        event.preventDefault();

    }        })

            function Delete() {
                var list = [];
                $('#userForm input:checked').each(function () {
                    list.push(this.id);

                });
                var parameters = {};
                if (url == '@Url.Action("DeleteUser", "UserManagement")') {
                parameters = JSON.stringify(list);
            }
            else {
                parameters = JSON.stringify({ "userId": list, "ISActive": IsActive });
            }
            $.ajax({
                url: url,
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                dataType: "html",
                traditional: true,
                data: parameters,
                success: function (data, textStatus, jqXHR) {
                    $('#updateAjax').html(data);
                },
                error: function (data) {
                    $('#updateAjax').html(data);

                }
            });   //end ajax
        }
        });
    </script>

//html // HTML

@using Common.UsersManagement.Entities;
@model IEnumerable<VwUser>
@{
    Layout = "~/Views/Shared/Master.cshtml";
}

    <form id="userForm">
        <div id="updateAjax">
@Html.AntiForgeryToken()
            @if (string.IsNullOrWhiteSpace(ViewBag.MessageResult) == false)
            {
                <div class="@ViewBag.cssClass">
                    @Html.Label(ViewBag.MessageResult as string)
                </div>
                <br />
            }
            <table class="table" cellspacing="0">
                @foreach (VwUser Item in Model)
                {   
                    <tr class="@(Item.IsActive ? "tRow" : "Disable-tRow")">
                        <td class="tbody">
                            <input type="checkbox" id="@Item.Id" name="selected"  value="@Item.FullName"/></td>
                        <td class="tbody">@Item.FullName</td>
                        <td class="tbody">@Item.Post</td>
                        <td class="tbody">@Item.Education</td>
                    </tr>
                }
            </table>
        </div>
        <br />
        <br />
    @if (!Request.IsAjaxRequest())
    {
        <div class="btnContainer">
            <a href="#" id="DeleteUser" class="insertBtn">delete  </a>
            <br />
            <br />
        </div>}

This might helpful for someone. 这可能对某人有帮助。 All you need to do is, add the following lines in your jquery and cshtml wherever it is appropriate. 您需要做的就是在适当的地方在jquery和cshtml中添加以下行。

jquery: jQuery的:

var token = $('#userForm input[name="__RequestVerificationToken"]').val();

// ....
//include {__RequestVerificationToken:token} in your json result. 
//For example,

JSON.stringify({ __RequestVerificationToken:token, "userId": list, "ISActive": IsActive })

cshtml: CSHTML:

<form id="userForm"> 
@Html.AntiForgeryToken()
        <div id="updateAjax">
    ...
</div>
</form>

Also, remove 另外,移除

contentType: "application/json; charset=utf-8"

Please read the below link https://nozzlegear.com/blog/send-and-validate-an-asp-net-antiforgerytoken-as-a-request-header 请阅读以下链接https://nozzlegear.com/blog/send-and-validate-an-asp-net-antiforgerytoken-as-a-request-header

Antiforgerytokens aren't checked by default with AJAX POST. 默认情况下,AJAX POST不检查防伪令牌。 You can enable it by overriding OnAuthorization like so: AJAX AntiforgeryToken 您可以通过重写OnAuthorization来启用它,如下所示: AJAX AntiforgeryToken

哇,这是带有附加信息的完整解决方案: http : //weblogs.asp.net/dixin/anti-forgery-request-recipes-for-asp-net-mvc-and-ajax

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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