Search code examples
ajaxasp.net-mvcantiforgerytoken

mvc-unable to call controller action having antiforgery token


I am sending my uploaded image to controller by ajax call if I remove antiforgery token from my controller everything works fine but if I use it call is not hit and I get 500 error.

Controller

   [ValidateAntiForgeryToken]
    [AuthenticationRequired]
    [HttpPost]
    public ActionResult ChangeProfilePicture(HttpPostedFileBase imageData)
    {
    }

View

  @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");
                }

            });
        }

    });
}

Solution

  • Your ajax call is not passing the token correctly. It needs to be

    ....
    data.append('__RequestVerificationToken', token);
    
    $.ajax({
        type: "POST",
        data: data,
        processData: false,
        ....