In this article I will explain with an example, how to use Antiforgery Token with submit in ASP.Net using C# and VB.Net.
Install Microsoft.AspNet.WebPages Nuget Package
First you need to install the
Microsoft.AspNet.WebPages package from
Nuget.
HTML Markup
The following HTML Markup consists of:
TextBox – For capturing Name.
DropDownList – For selecting Country to be submit.
Button – For submitting the Form.
The Button has been assigned with an OnClick event handler.
The Anti-Forgery Token has been added to the HTML using the GetHtml method of the AntiForgery class.
Note: The AntiForgeryToken function generates a HiddenField with the AntiForgery Token.
<%= System.Web.Helpers.AntiForgery.GetHtml()%>
<table>
<tr>
<td>Name:</td>
<td><asp:TextBox ID="txtName" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td>Country:</td>
<td>
<asp:DropDownList ID="ddlCountries" runat="server">
<asp:ListItem Text="Please select" Value=""></asp:ListItem>
<asp:ListItem Text="United States" Value="United States"></asp:ListItem>
<asp:ListItem Text="India" Value="India"></asp:ListItem>
<asp:ListItem Text="France" Value="France"></asp:ListItem>
<asp:ListItem Text="Russia" Value="Russia"></asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td></td>
<td><asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="OnSubmit" /></td>
</tr>
</table>
Namespaces
You will need to import the following namespace.
C#
using System.Web.Helpers;
VB.Net
Imports System.Web.Helpers
Assigning AntiForgery in Page Load
Inside the Page_Load event handler, Validate method of AntiForgery class is called to prevent cross-site request forgery attacks inside the IsPostBack condition.
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.
C#
protected void Page_Load(object sender, EventArgs EventArgs e)
{
if (this.IsPostBack)
{
// Throws Exception if AntiForgery check fails.
AntiForgery.Validate();
}
}
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs)
If Me.IsPostBack Then
' Throws Exception if AntiForgery check fails.
AntiForgery.Validate()
End If
End Sub
Submitting the Form
When the Button is clicked, value of the Name and Country are fetched from their respective controls and displayed using
JavaScript Alert Message Box using
RegisterStartupScript method of
ClientScript class.
C#
protected void OnSubmit(object sender, EventArgs e)
{
string name = txtName.Text;
string country = ddlCountries.SelectedItem.Text;
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Customer inserted successfully.');", true);
}
VB.Net
Protected Sub OnSubmit(sender As Object, e As EventArgs)
Dim name As String = txtName.Text
Dim country As String = ddlCountries.SelectedItem.Text
ClientScript.RegisterStartupScript(Me.GetType(), "alert", "alert('Customer inserted successfully.');", True)
End Sub
Screenshot
Downloads