Send AntiForgeryToken via jQuery Ajax in ASP.NET Core

In ASP.NET Core, if we use jQuery Ajax to post data to the server, and we want the ValidateAntiForgeryToken attribute to work. We have to do some tricks. The official document didn't document how to do it via jQuery. Let me show you how to do it.

The backend Controller will use these names to validate the request. And I don't want to forget to change every place where there is a manual written input tag. So basically, @Html.AntiForgeryToken() will generate HTML based on my definition in Startup.cs like this. And if some day I changed the name in antiforgery options, I don't need to worry about forget to change it everywhere in my cshtml pages.

Many thanks. We where test crawling our website and noticed a difference in the URLs. Now we know why :) It's already hard to keep consistency when developing applications in a team. Now even need to be more careful with selecting which UrlEncode to use by default.