新文章 网摘 文章 随笔 日记

使用$.ajax提交时提示Bad Request 400,后台使用了ValidateAntiForgeryToken的解决方案

一、在_Layout.cshtml中加入

 

    <!-- used for ajax in AddAntiForgeryToken()-->
    <form id="__AjaxAntiForgeryForm" action="#" method="post">@Html.AntiForgeryToken()</form>
    <script type="text/javascript">
        $(document).ready(function () {
            var securityToken = $('[name=__RequestVerificationToken]').val();
            $(document).ajaxSend(function (event, request, opt) {
                if (opt.hasContent && securityToken) {   // handle all verbs with content
                    var tokenParam = "__RequestVerificationToken=" + encodeURIComponent(securityToken);
                    opt.data = opt.data ? [opt.data, tokenParam].join("&") : tokenParam;
                    // ensure Content-Type header is present!
                    if (opt.contentType !== false || event.contentType) {
                        request.setRequestHeader("Content-Type", opt.contentType);
                    }
                }
            });
        });
    </script>

二、后台Action中

     [HttpPost]
     [ValidateAntiForgeryToken]

三、提交时:

@section Scripts {

    <script type="text/javascript">
        (function (window, $, options) {
            $(document).ready(function () {
                $('.delete').click(function (e) {
                    if (confirm('确实要删除这个路由?')) {
                        var id = $(e.currentTarget).data('id');
                        $.ajax({
                            url: '@Url.Action("Delete")',
                            type: "POST",
                            data: { id: id },
                            dataType: "json",
                            success: function (data, status) {
                                alert(data);
                            },
                            error: function (data, status) {
                                alert("Data: " + data + "nStatus: " + status);
                            }
                        });
                    };
                });
            });
        })(window, jQuery);
    </script>
}

 https://stackoverflow.com/questions/4074199/jquery-ajax-calls-and-the-html-antiforgerytoken

posted @ 2020-03-13 09:46  岭南春  阅读(286)  评论(0)    收藏  举报