In this article I will explain with an example, how to use AntiForgery Token with Submit in ASP.Net Core (.Net Core 8).
Controller
The Controller consists of following 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 lastName);
return View();
}
}
View
HTML Markup
The View consists of an HTML Form which has been created using the ASP.Net TagHelpers 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 Anti-Forgery Token has been added to the View using the AntiForgeryToken function of the HTML Helper class.
Note: The AntiForgeryToken function generates an HiddenField with the AntiForgery Token.
The HTML of Form consists of following elements.
TextBox – For user input.
Button – For submitting the form.
Submitting the form
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" asp-controller="Home" asp-action="Index">
@Html.AntiForgeryToken()
<table>
<tr>
<td>First Name:</td>
<td>><> 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