Essentially, I am having an issue with validating the token in my JavaScript code. Everything works fine without validation, but once I try to validate the token, I receive an error stating
The required anti-forgery form field "__RequestVerificationToken" is not present.
var downloadEmailSignature = function (control) {
if (control) {
let form = $(control).closest('form');
let token = $(form).find('input[name="__RequestVerificationToken"]').val();
if (form) {
let request = new XMLHttpRequest();
request.open("POST", "Forms/DownloadEmailSignature");
request.responseType = "blob";
request.setRequestHeader('RequestVerificationToken', token);
request.data = form.serialize();
request.onload = function () {
if (window.clientData.browser.name === "Internet Explorer") {
window.navigator.msSaveBlob(this.response, "EmailSignature.hta");
}
else{
let url = window.URL.createObjectURL(this.response);
let a = document.createElement("a");
document.body.appendChild(a);
a.href = url;
a.download = this.response.name || "download-" + $.now();
a.click();
}
};
console.dir(request);
request.send();
}
}
};
Here is the corresponding backend code...
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult DownloadEmailSignature(string emailSignature)
{
var hta = (MediaItem)SitecoreContext.GetItem<Item>(new Guid("{EE806F14-5BD3-491C-9169-DA701357FB45}"));
using (var reader = new StreamReader(MediaManager.GetMedia(hta).GetStream().Stream))
{
var htaText = reader.ReadToEnd();
htaText = htaText.Replace("*CARDSTRING*", emailSignature);
var stream = new MemoryStream(htaText.ToASCIIByteArray());
return new FileStreamResult(stream, "application/hta");
}
}
Lastly, here is the view section...
<form id="download-email-signature" method="POST" enctype="multipart/form-data">
@Html.HiddenFor(m => m.EmailSignatureMarkup)
@Html.AntiForgeryToken()
@Html.FormIdentifier("FormsController", "DownloadEmailSignature")
<a href="#" id="download-installer" onclick="downloadEmailSignature(this); return false;" class="btn-primary" style="margin-bottom:10px;margin-top:-10px;text-align:center;">Download installer</a>
</form>