November 2015
Intermediate to advanced
152 pages
2h 46m
English
It is very common to use AJAX to post data to or get data from the server. An AJAX request sends the JSON data to server. It doesn't send the HTML form data. To achieve sending the token via an AJAX post, we need to use the custom HTTP header. Using Razor syntax, we can generate the tokens by calling the AntiForgery.GetTokens() method and attach it to the request as given in the following code:
<script> @functions{ public string GetAntiForgeryTokenValue () { string tokenInCookie, tokenInForm; AntiForgery.GetTokens(null, out tokenInCookie, out tokenInForm); return tokenInCookie + ":" + tokenInForm; } } $.ajax("/api/contacts", { type: "get", headers: { 'AntiForgeryToken': '@GetAntiForgeryTokenValue()' }, success: function ...Read now
Unlock full access