通过AJAX发布时,MVC防伪令牌不允许上传多个文件

时间:2019-02-06 18:34:42

标签: c# ajax model-view-controller csrf antiforgerytoken

我知道上传多个文件效果很好,因为当我注释掉时 [ValidateAntiForgeryToken]我可以选择多个文件,它们将被上传而没有任何问题。

但是,当我将[ValidateAntiForgeryToken]放回If I select 2 or more files时,我得到了服务器500 status error,但没有文件上传。

此外,我将添加错误: Failed to load resource: the server responded with a status of 500 (Internal Server Error)堆栈跟踪表明它已停止在line 1 of Upload action

但是,如果我选择1个文件,则该文件将成功上传并且得到status code 200

我对此还很陌生-我不知道出什么问题了。我感谢对这个谜的任何帮助。 :-)

这是我的控制器操作:

[HttpPost]
[ValidateAntiForgeryToken]   // If I comment this out, everything works as intended
public ActionResult Upload()
{
    for (int i = 0; i < Request.Files.Count; i++)
    {
        var file = Request.Files[i];

        var fileName = Path.GetFileName(file.FileName);

        var path = Path.Combine(Server.MapPath("~/Some/FilePath"), fileName);
        file.SaveAs(path);
    }

    return Json(new { success = true, responseText = "Success!" }, JsonRequestBehavior.AllowGet); //This is placeholder, I'll implement validation later
}

HTML:

@Html.TextBoxFor(model => model.file, new { type = "file", id = "file-upload", multiple="multiple" })
@Html.ValidationMessageFor(model => model.file, "", new { @class = "text-danger" })

<div id="selectedFiles"></div>

我构建了自定义文件Array,因此可以使用精美的删除文件功能。 这就是我调用UploadAjax函数的方式:

var storedFiles = [];    //this is what I pass to it.

$("#stupidTest").click(function () {
    UploadAjax(storedFiles);
});

JQuery,AJAX。这是上传功能。

function UploadAjax(storedFilesArray) {
    var formData = new FormData();

    for (let i = 0; i < storedFilesArray.length; i++) {
        let file = storedFilesArray[i];

        formData.append('__RequestVerificationToken', getToken()); //appends the value to the formData. 
        formData.append("file-upload", file);
    }
    $.ajax({
        type: "POST",
        dataType: 'json',
        cache: false,
        url: '/Home/Upload',
        data: formData,
        contentType: false,
        processData: false,
        success: function (response) {
            ...
        },
        error: function (response) {
            ...
        }
    });
}

**Edit: Found that this happened at the same second my multiple file upload request failed**

System.Web.Mvc.HttpAntiForgeryException: The anti-forgery token could not be
decrypted. If this application is hosted by a Web Farm or cluster, ensure that
all machines are running the same version of ASP.NET Web Pages and that the
<machineKey> configuration specifies explicit encryption and validation keys.
AutoGenerate cannot be used in a cluster.

2 个答案:

答案 0 :(得分:1)

将此行带出循环(并将其置于循环的上方或下方):

formData.append('__RequestVerificationToken', getToken()); //appends the value to the formData.

append将继续添加到提交给服务器的__RequestVerificationToken值上。一旦将其附加到一次(即,如果您选择了2个或更多文件),则该值将不是有效的XSRF防伪令牌。然后它无法验证,因此您在服务器上收到错误。

答案 1 :(得分:1)

也许您应该在周期之外设置formData.append('__RequestVerificationToken', getToken());

var formData = new FormData();
formData.append('__RequestVerificationToken', getToken()); //appends the value to the formData. 
for (let i = 0; i < storedFilesArray.length; i++) {
        let file = storedFilesArray[i];
         formData.append("file-upload", file);
    }