Why my ASP.net core application does not accept manually generated tokens
You can get token from form element:
TokenController.cs
public class TokenController : Controller
{
[HttpGet]
[Route("[controller]")]
public ActionResult Index()
{
return PartialView("Token");
}
}
Token.cshtml:
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
<form method="post"></form>
js:
$.ajax = function(options)
{
return new Promise(async (resolve, reject) =>
{
var xhr = new XMLHttpRequest();
xhr.onerror = function()
{
//...
};
xhr.onload = function()
{
//...
};
if (options.method.toLowerCase() === 'get')
{
xhr.open(options.method, `${options.url}?${$.param(options.data)}`, true);
xhr.send();
}
else
{
var $tokenField = $(`[name="FieldToken"]`);
if ($tokenField.length === 0)
{
await $.ajax({
url: 'Token/GetHeaderToken',
method: 'get',
complete: function(x)
{
$('body').append(x.responseText);
}
});
$tokenField = $(`[name="FieldToken"]`);
}
xhr.open(options.method, options.url, true);
xhr.setRequestHeader("HeaderToken", $tokenField.first().val());
xhr.send(getFormData(options.data));
}
});
};