c# – 如何通过jquery ajax发送AntiForgeryToken(CSRF)和FormData

前端之家收集整理的这篇文章主要介绍了c# – 如何通过jquery ajax发送AntiForgeryToken(CSRF)和FormData前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
所以我想通过 AJAX将FileUpload与AntiForgeryToken一起发布.这是我的代码

视图

@using (Html.BeginForm("Upload","RX",FormMethod.Post,new {id = "frmRXUpload",enctype = "multipart/form-data"}))
{
     @Html.AntiForgeryToken()
     @Html.TextBoxFor(m => m.RXFile,new {.type = "file"})
     ...rest of code here
}

<script>
    $(document).ready(function(){
        $('#btnRXUpload').click(function () {
            var form = $('#frmRXUpload')

            if (form.valid()) {
                var formData = new FormData(form);
                formData.append('files',$('#frmRXUpload input[type="file"]')[0].files[0]);
                formData.append('__RequestVerificationToken',fnGetToken());

                $.ajax({
                    type: 'POST',url: '/RX/Upload',data: formData,contentType: false,processData: false
                })
            }
        })
    })
</script>

调节器

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Upload()
{
    //rest of code here
}

我明白了

The anti-forgery token could not be decrypted. If this application is hosted by a Web Farm or cluster

通过提琴手的错误.不知道如何解决这个问题?

我发现了答案:

<script>
        $(document).ready(function(){
            $('#btnRXUpload').click(function () {
                var form = $('#frmRXUpload')

                if (form.valid()) {
                    var formData = new FormData(form.get(0)); //add .get(0)
                    formData.append('files',$('#frmRXUpload input[type="file"]')[0].files[0]);

                    $.ajax({
                        type: 'POST',processData: false
                    })
                }
            })
        })
    </script>

解决方法

最后发现答案:

我只需要在表单中添加.get(0),这里是代码

<script>
        $(document).ready(function(){
            $('#btnRXUpload').click(function () {
                var form = $('#frmRXUpload')

                if (form.valid()) {
                    var formData = new FormData(form.get(0)); //add .get(0)
                    formData.append('files',$('#frmRXUpload input[type="file"]')[0].files[0]);
                    //formData.append('__RequestVerificationToken',fnGetToken()); //remark this line

                    $.ajax({
                        type: 'POST',processData: false
                    })
                }
            })
        })
    </script>

猜你在找的C#相关文章