ajax - Enable Antiforgery Token with ASP.NET Core and JQuery -
i using jquery asp.net core 1.0.1 , have 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) { // send message }
the form in shared view , following:
<form id="send-question" method="post"> <textarea name="content"></textarea> <button class="button" type="submit">enviar</button> </form>
when submit form error:
microsoft.aspnetcore.antiforgery.antiforgeryvalidationexception: required antiforgery header value "requestverificationtoken" not present.
how can enable asp.net core's antiforgerytoken jquery ajax calls?
update
i need add following asp-controller , asp-action form:
<form asp-controller="questionapi" asp-action="post" id="send-question" method="post"> </form>
this generate antiforgery token. , needed manually add token headers of jquery call follows:
headers: { "accept": "application/json", "content-type": "application/json", "requestverificationtoken": $form.find("input[name='af_token']").val() },
is there better way this?
how solve when there not form , have tag when clicked makes ajax call? can generate common antiforgery token on page head used ajax calls page?
mode777's answer needs small addition make work (i tried it):
$(document).ajaxsend(function(e, xhr, options) { if (options.type.touppercase() == "post") { var token = $form.find("input[name='af_token']").val(); xhr.setrequestheader("requestverificationtoken", token); } });
actually, if submit using ajax, don't need use form @ all. put in _layout:
<span class="antiforge"> @html.antiforgerytoken() </span>
then pickup token adding javascript:
$(document) .ajaxsend(function (event, jqxhr, settings) { if (settings.type.touppercase() != "post") return; jqxhr.setrequestheader('requestverificationtoken', $(".antiforge" + " input").val()) })
the @htmlantiforgerytoken generates hidden input field antiforgery token, same when using form. code above finds using class selector select span, gets input field inside collect token , add header.
Comments
Post a Comment