Ravi Vishwakarma is a dedicated Software Developer with a passion for crafting efficient and innovative solutions. With a keen eye for detail and years of experience, he excels in developing robust software systems that meet client needs. His expertise spans across multiple programming languages and technologies, making him a valuable asset in any software development project.
ICSM Computer
10-Jun-2025In ASP.NET Web API (not MVC),
@Html.AntiForgeryToken()does not apply directly because Web API does not use Razor views or MVC forms by default.However, you can integrate anti-forgery protection into Web API by manually validating anti-forgery tokens for APIs that are accessed via AJAX (e.g., from MVC views or SPAs).
Goal: Use Anti-Forgery Token in Web API
Step 1: Generate the Token in MVC View
If your front-end uses Razor (MVC view), generate the anti-forgery token using:
This emits two things:
__RequestVerificationToken__RequestVerificationTokenStep 2: Send Token with AJAX Request
In JavaScript, extract the token from the cookie or form and send it as a header:
Step 3: Validate the Token in Web API
Create a custom filter attribute to validate the anti-forgery token:
Step 4: Apply the Attribute to API Methods
Summary
@Html.AntiForgeryToken()AntiForgery.Validate(cookie, token)