Short answer is No. There is no browser-side facility for setting arbitrary HTTP Request Headers when submitting a form.
Besides, if you don't have any special setting in asp.net core. The ValidateAntiForgeryToken will check the formdata's __RequestVerificationToken
instead of the header XSRF-TOKEN
.
This is how validate AntiForgery works:
1.The client requests an HTML page that contains a form.
2.The server includes two tokens in the response. One token is sent as a cookie. The other is placed in a hidden form field. The tokens are generated randomly so that an adversary cannot guess the values.
3.When the client submits the form, it must send both tokens back to the server. The client sends the cookie token as a cookie, and it sends the form token inside the form data. (A browser client automatically does this when the user submits the form.)
4.If a request does not include both tokens, the server disallows the request.
So the most easily way is set the token as the hidden field and postback like below:
@Html.AntiForgeryToken()
<input type="button" onclick="dynamicallyPostForm('TestWithAnti', {name: 'Johnny Bravo'});" />
@section scripts{
<script>
function dynamicallyPostForm(path, params, method = 'post') {
const form = document.createElement('form');
form.method = method;
form.action = path;
for (const key in params) {
if (params.hasOwnProperty(key)) {
const hiddenField = document.createElement('input');
hiddenField.type = 'hidden';
hiddenField.name = key;
hiddenField.value = params[key];
form.appendChild(hiddenField);
}
}
//get the token and append into new form
const hiddenField = document.createElement('input');
hiddenField.type = 'hidden';
hiddenField.name = '__RequestVerificationToken';
hiddenField.value = document.getElementsByName('__RequestVerificationToken')[0].value;
form.appendChild(hiddenField);
document.body.appendChild(form);
form.submit();
}
</script>
}
Result:
