In this article I will explain with an example, how to implement AntiForgery Token in ASP.Net Core MVC.
Controller
The Controller consists of two Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
Action method for handling POST operation
The Action method for POST operation accepts the values of First Name and Last Name sent from the View and it is assigned to a ViewBag object.
Attributes
The Action method is decorated with the following attributes.
HttpPost: The HttpPost attribute which signifies that the method will accept Http Post requests.
ValidateAntiForgeryToken: The ValidateAntiForgeryToken attribute is used to prevent cross-site request forgery attacks.
Note: A cross-site request forgery is an attack is done by sending harmful script element, malicious command, or code from the user’s browser.
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Index(string firstName, string lastName)
{
ViewBag.Name = string.Format("Name: {0} {1}", firstName, lastName);
return View();
}
}
View
The View consists of an HTML Form which has been created using the Razor Tag attributes with the following attributes.
asp-action – Name of the Action. In this case the name is Index.
asp-controller – Name of the Controller. In this case the name is Home.
method – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
The AntiForgery Token has been added to the View using the AntiForgeryToken function of the HTML Helper class.
Inside the Form, there are two TextBox fields created for capturing values for First Name and Last Name. Both TextBoxes have been specified with Name attribute which will be required to fetch the TextBox values inside the Controller.
There’s also a Submit Button at the end of the Form and when the Button is clicked, the Form is submitted.
Finally, the value of the ViewBag object is displayed using Razor syntax.
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form method="post" enctype="multipart/form-data" asp-controller="Home" asp-action="Index">
@Html.AntiForgeryToken()
<table>
<tr>
<td>First Name: </td>
<td><input type="text" id="txtFirstName" name="FirstName" /></td>
</tr>
<tr>
<td>Last Name: </td>
<td><input type="text" id="txtLastName" name="LastName" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit"/></td>
</tr>
</table>
<hr/>
@ViewBag.Name
</form>
</body>
</html>
Screenshot
Downloads