MVC HtmlHelper.AntiForgeryToken tutorial with examples

In web development, security is a major concern. One of the most critical aspects of security is preventing Cross-Site Request Forgery (CSRF) attacks. In ASP.NET MVC, the @Html.AntiForgeryToken helper method can help protect against CSRF attacks by generating a token that is sent to the client and verified on the server.

What is CSRF?

CSRF is a type of attack where a malicious website can trick a user into performing actions on another website where the user is already authenticated. For example, a user might be logged into an online banking site, and a malicious website could trick the user into making a transfer of funds to a different account.

How does @Html.AntiForgeryToken work?

The @Html.AntiForgeryToken helper method generates a token that is sent to the client and verified on the server. The token is a unique string of characters that is generated by the server and sent to the client as a hidden field in the form. The client sends the token back to the server with each request, and the server verifies the token before processing the request.

Code Example

In the following example, the @Html.AntiForgeryToken method is used in a form in an ASP.NET MVC view. The form is used to create a new user account.
<form action="CreateUser" method="post">

In the controller action that handles the form submission, the ValidateAntiForgeryToken attribute is used to verify the token.
public ActionResult CreateUser(string username, string password)
  // Code to create the user account goes here
  return View();


The @Html.AntiForgeryToken helper method is an important tool for preventing CSRF attacks in ASP.NET MVC. By generating a unique token and verifying it on the server, developers can help ensure the security of their web applications and protect their users from malicious attacks.

For complete information about HtmlHelper.AntiForgeryToken method you can check this: HtmlHelper.AntiForgeryToken Method
Best quality Asp .Net Ajax Control Toolkit tutorials.

Give your valuable comments.

1 + 7 =

About Us | Terms of Use | Privacy Policy | Disclaimer | Contact Us Copyright © 2012-2024 CodingFusion
50+ C# Programs for beginners to practice