By default, jQuery will send any data in a $.post as x-www-form-urlencoded. I'm not a big fan of that, mostly because it's much more difficult for humans to parse when compared to JSON. That's why I've started extending jQuery with a custom $.postJson method:
But if we're using ASP.NET, we wind up running into a problem when sending JSON data rather than form-encoded data: by default, ASP.NET will not read the AntiForgeryToken when it's sent as JSON.
That means that any time you send JSON and want to validate the token your request will automatically fail by tripping the ValidateAntiForgeryToken method; ASP.NET assumes that any request with an absent validation token is something called a Cross-Site Request Forgery (CSRF) attack.
Turning the token validation off isn't an option, because doing so will leave your web application more vulnerable to these CSRF attacks. We can fix that pretty easily though by adding a single parameter to the function, and then adding that value as a request header whenever it's present.
And we can use our new $.postJson function like so:
NB: Don't forget to add "@Html.AntiForgeryToken()" to your view, or the token won't be present on the page and therefore can't be sent as a header.
But we're not quite done. Just because we've added the token as a request header doesn't mean that ASP.NET knows to look for it there. We'll need to create a custom attribute that will specifically look in the request headers for our anti-forgery token.
Then you simply mark your controller's action method with the [ValidateHeaderAntiForgeryToken] attribute.
That's it! You can now easily use jQuery to send form data as JSON by default and still protect your web application from Cross-Site Request Forgery attacks.
P.S. If you're using TypeScript and want to get type-checking and intellisense for $.postJson, you can add the following to your jquery.d.ts file (or any other appropriate definition file):
I'm writing a book called The Shopify Development Handbook, and it's all about building rock-solid Shopify apps with C# and ASP.NET. If you haven't done so already, join the mailing list below by typing in your email address. I'll send you a free developer's guide on using the Shopify billing API to get paid for your app.
Learn how to build rock solid Shopify apps with C# and ASP.NET!
Did you enjoy this article? I wrote a premium course for C# and ASP.NET developers, and it's all about building rock-solid Shopify apps from day one.
Enter your email here and I'll send you a free sample from The Shopify Development Handbook. It'll help you get started with integrating your users' Shopify stores and charging them with the Shopify billing API.