I am using jQuery with ASP.NET Core 1.0.1, and I have an Ajax call:
$("#send-message").on("submit", function (event) { event.preventDefault(); var $form = $(this); $.ajax({ url: "api/messages", data: JSON.stringify($form.serializeToJSON()), dataType: "json", headers: { Accept: "application/json", "Content-Type": "application/json" }, type: "post" }) .done(function (data, status, xhr) { }) .fail(function (xhr, status, error) { });
To ASP.NET Core Action:
[HttpPost("messages")] public async Task<IActionResult> Post([FromBody]MessagePostApiModelModel model) {
The form is in general view, and it looks like this:
<form id="send-question" method="post"> <textarea name="content"></textarea> <button class="button" type="submit">Enviar</button> </form>
When I submit the form, I get an error message:
Microsoft.AspNetCore.Antiforgery.AntiforgeryValidationException: The required antiforgery header value "RequestVerificationToken" is not present.
How to enable ASP.NET Core AntiForgeryToken using jQuery Ajax calls?
UPDATE
I need to add the following asp-controller and asp-action to the form:
<form asp-controller="QuestionApi" asp-action="Post" id="send-question" method="post"> </form>
This will create an antiforgery token. And I needed to manually add the token to the jQuery call headers as follows:
headers: { "Accept": "application/json", "Content-Type": "application/json", "RequestVerificationToken": $form.find("input[name='af_token']").val() },
Is there a better way to do this?
How to solve this problem when there is no form, and I only have the A tag, which when clicked causes an Ajax call? Can I generate a common anti-corrosion token on my page to use all ajax calls from this page?