我通过ajax调用将上传的图像发送到控制器如果我从控制器中删除防伪令牌一切正常但是如果我使用它则调用未被命中且我得到500错误。
控制器
[ValidateAntiForgeryToken]
[AuthenticationRequired]
[HttpPost]
public ActionResult ChangeProfilePicture(HttpPostedFileBase imageData)
{
}
查看
@Html.AntiForgeryToken()
<div class="modal-body" id="tilesDescription">
<div class="row">
<div class="col-md-12">
<div class="text-center">
<div class="fileUpload btn btn-primary">
<span>Select a photo from your computer</span>
<input id="uploadBtn" type="file" class="upload" name="imageData" accept="image/*" />
</div>
<div class="text-center">
<img id="imgprvw" alt="uploaded image preview" class="imgPreview hide" />
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-rounded btn-sm btn-tiles" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-rounded btn-sm btn-tiles disabled" id="btnProfilePic" onclick=" changeProfilePic() ">Set as profile picture</button>
</div>
ajax call
function changeProfilePic() {
var data = new FormData();
data.append("imageData", file);
//var form = $('#__AjaxAntiForgeryForm');
var token = $('[name=__RequestVerificationToken]').val();
console.log($('[name=__RequestVerificationToken]').val());
data[" __RequestVerificationToken"]= token;
console.log(data[" __RequestVerificationToken"]);
$.ajax({
type: "POST",
data: data,
processData: false,
contentType: false,
url: '@Url.Action("ChangeProfilePicture", "Account")',
success: function (resultdata) {
HideModelWindow();
$.ajax({
type: "POST",
url: '@Url.Action("SetProfilePicture", "Account")',
success: function (resultdata) {
$("#profilePicDiv").empty();
$("#profilePicDiv").append(resultdata);
alert("Profile picture changed successfully");
}
});
}
});
}
答案 0 :(得分:2)
您的ajax调用未正确传递令牌。它必须是
....
data.append('__RequestVerificationToken', token);
$.ajax({
type: "POST",
data: data,
processData: false,
....