Asp.Net Mvc Form Submission And Anti Forgery Tokens Complete Guide

 Last Update:2025-06-23T00:00:00     .NET School AI Teacher - SELECT ANY TEXT TO EXPLANATION.    8 mins read      Difficulty-Level: beginner

Understanding the Core Concepts of ASP.NET MVC Form Submission and Anti Forgery Tokens

Explaining ASP.NET MVC Form Submission and Anti Forgery Tokens

Form Submission in ASP.NET MVC

When building applications using ASP.NET MVC, form submission is a common task. Forms allow users to enter data, which is then sent to the server for processing. In ASP.NET MVC, forms can be generated using HTML helpers such as Html.BeginForm() within the Razor view engine. This helper method takes care of generating HTML form tags and handling their routing and method attributes.

For example:

@using (Html.BeginForm("UpdateProfile", "User", FormMethod.Post))
{
    <label>Name</label>
    <input type="text" name="name" />
    <input type="submit" value="Update Profile" />
}

The above code snippet creates a form that submits data to the UpdateProfile action method in the User controller using the POST method.

Anti Forgery Tokens in ASP.NET MVC

One critical security concern with form submissions is Cross-Site Request Forgery (CSRF) attacks. A CSRF attack forces an end user to execute unwanted actions on a web application in which they're authenticated. For instance, a logged-in user could be tricked into submitting a form that transfers money to an attacker's account.

To mitigate CSRF, ASP.NET MVC provides anti-forgery tokens. These tokens are unique, unpredictable values that are embedded within a form when it is rendered on the client side. Upon form submission, the server validates the anti-forgery token to ensure that the request is coming from a legitimate source and not part of a CSRF attack.

To implement anti-forgery tokens, you first need to decorate the controller action that will handle the form submission with the [ValidateAntiForgeryToken] attribute. Next, you need to include the anti-forgery token in the form using the Html.AntiForgeryToken() HTML helper method.

Here's how to utilize anti-forgery tokens in your ASP.NET MVC application:

  1. Decorate the Controller Action:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult UpdateProfile(string name)
{
    // Process the form submission
    return View();
}
  1. Include the Anti-Forgery Token in the Form:
@using (Html.BeginForm("UpdateProfile", "User", FormMethod.Post))
{
    @Html.AntiForgeryToken()
    <label>Name</label>
    <input type="text" name="name" />
    <input type="submit" value="Update Profile" />
}

When rendered, the Html.AntiForgeryToken() method will generate hidden HTML fields containing the anti-forgery token, similar to:

<form action="/User/UpdateProfile" method="post">
    <input name="__RequestVerificationToken" type="hidden" value="unique_token_value" />
    <label>Name</label>
    <input type="text" name="name" />
    <input type="submit" value="Update Profile" />
</form>

The server will check the submitted form for the correct anti-forgery token. If the token is missing or invalid, the request will be rejected.

Importance of Anti Forgery Tokens

Anti-forgery tokens play a crucial role in securing ASP.NET MVC applications against CSRF attacks. By validating the token, developers can ensure that form submissions originate from a trusted source and are not part of a malicious attempt to manipulate the server's state.

Online Code run

🔔 Note: Select your programming language to check or run code at

💻 Run Code Compiler

Step-by-Step Guide: How to Implement ASP.NET MVC Form Submission and Anti Forgery Tokens


Step 1: Setting Up Your ASP.NET MVC Project

  1. Create a new project:

    • Open Visual Studio.
    • Go to File > New > Project.
    • Choose ASP.NET Web Application (.NET Framework).
    • Enter the project name and click OK.
    • Select MVC template and make sure Authentication is set to No Authentication.
  2. Install necessary packages:

    • By default, ASP.NET MVC projects have most of what you need to work with forms and anti-forgery tokens included. However, if you need any additional packages, you can install them via NuGet Package Manager.

Step 2: Creating the Model

For this example, let's create a simple model for handling user data.

// Models/UserModel.cs
namespace MvcFormSubmission.Models
{
    public class UserModel
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
    }
}

Step 3: Creating the Controller

Next, we'll create a controller that will handle form submission.

// Controllers/UserController.cs
using System.Web.Mvc;
using MvcFormSubmission.Models;

namespace MvcFormSubmission.Controllers
{
    [ValidateAntiForgeryToken]
    public class UserController : Controller
    {
        // GET: /User/Register
        [HttpGet]
        public ActionResult Register()
        {
            return View();
        }

        // POST: /User/Register
        [HttpPost]
        public ActionResult Register(UserModel user)
        {
            if (ModelState.IsValid)
            {
                // Here you would typically save the user to the database
                ViewBag.Message = "Registration successful!";
                return View(user);
            }

            // If not valid, return the same view with validation messages
            ViewBag.Error = "Please correct the errors below.";
            return View(user);
        }
    }
}

Step 4: Creating the View

Now, let's create a view for user registration.

  1. Right-click the Register action method:

    • Choose Add View....
  2. Configure the view:

    • Set the view name to Register.
    • Select Strongly typed and choose UserModel as the model class.
    • Click Add.

Here's the code for the view:

<!-- Views/User/Register.cshtml -->
@model MvcFormSubmission.Models.UserModel
@{
    ViewBag.Title = "Register";
}

<h2>@ViewBag.Title</h2>

@if (!string.IsNullOrWhiteSpace(ViewBag.Message))
{
    <div style="color: green;">@ViewBag.Message</div>
}

@if (!string.IsNullOrWhiteSpace(ViewBag.Error))
{
    <div style="color: red;">@ViewBag.Error</div>
}

@using (Html.BeginForm("Register", "User", FormMethod.Post))
{
    @Html.AntiForgeryToken()

    <div>
        @Html.LabelFor(m => m.FirstName)
        @Html.TextBoxFor(m => m.FirstName, new { @class = "form-control" })
        @Html.ValidationMessageFor(m => m.FirstName)
    </div>

    <div>
        @Html.LabelFor(m => m.LastName)
        @Html.TextBoxFor(m => m.LastName, new { @class = "form-control" })
        @Html.ValidationMessageFor(m => m.LastName)
    </div>

    <div>
        @Html.LabelFor(m => m.Email)
        @Html.TextBoxFor(m => m.Email, new { @class = "form-control", type = "email"})
        @Html.ValidationMessageFor(m => m.Email)
    </div>

    <input type="submit" value="Register" class="btn btn-primary" />
}

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Step 5: Configuring Anti-Forgery Tokens

The anti-forgery token mechanism is already integrated into the example above with the use of @Html.AntiForgeryToken() helper method in the view and [ValidateAntiForgeryToken] attribute on the POST action method in the controller.

Let’s ensure that these mechanisms are configured properly.

Controller Configuration

Make sure your controller has the [ValidateAntiForgeryToken] attribute applied to the POST action method to verify the anti-forgery token:

// Controllers/UserController.cs
[ValidateAntiForgeryToken]
public ActionResult Register(UserModel user)
{
    if (ModelState.IsValid)
    {
        // Save the user to the database (not implemented here)
        ViewBag.Message = "Registration successful!";
        return View(user);
    }

    // If not valid, return the same view with validation messages
    ViewBag.Error = "Please correct the errors below.";
    return View(user);
}

View Configuration

Use the @Html.AntiForgeryToken() helper method to include an anti-forgery token in your form:

<!-- Views/User/Register.cshtml -->
@using(Html.BeginForm("Register", "User", FormMethod.Post)) 
{
    @Html.AntiForgeryToken()

    <div>
        @Html.LabelFor(m => m.FirstName)
        @Html.TextBoxFor(m => m.FirstName, new { @class = "form-control" })
        @Html.ValidationMessageFor(m => m.FirstName)
    </div>

    <div>
        @Html.LabelFor(m => m.LastName)
        @Html.TextBoxFor(m => m.LastName, new { @class = "form-control" })
        @Html.ValidationMessageFor(m => m.LastName)
    </div>

    <div>
        @Html.LabelFor(m => m.Email)
        @Html.TextBoxFor(m => m.Email, new { @class = "form-control", type = "email" })
        @Html.ValidationMessageFor(m => m.Email)
    </div>

    <input type="submit" value="Register" class="btn btn-primary" />
}

Step 6: Running the Project

Now it's time to test our application.

  1. Run the application:

    • Press F5 or click Start in Visual Studio.
  2. Navigate to the registration page:

    • The default route typically points to Home/Index. To navigate to the registration page, go to http://localhost:xxxx/User/Register, where xxxx is your port number.
  3. Test the form submission:

    • Fill out the form and submit it.
    • Ensure that the form does not submit when the anti-forgery token is missing or invalid.

Additional Considerations

  • Validation: The use of @Scripts.Render("~/bundles/jqueryval") ensures client-side validation based on the model data annotations (e.g., [Required]). You can add data annotations to your UserModel if needed.

  • Global Configuration: Anti-forgery tokens are globally enabled by default in ASP.NET MVC projects. However, you can configure them explicitly in Web.config:

You May Like This Related .NET Topic

Login to post a comment.