You are on page 1of 7

Using the Form Tag Helpers

• MVC provides a set of built-in tag helpers that are used to


perform commonly required transformations on HTML
elements. In this chapter, I describe the tag helpers that
operate on HTML forms, which include the form, input,
label, select, option, and textarea elements.

1
Working with Form Elements
• The FormTagHelper class is the built-in tag helper for form
elements and is used to manage the configuration of HTML
forms so that they target the right action method based on
the application’s routing configuration. This tag helper
supports the attributes described in Table 24-3.

2
Setting the Form Target
• The main purpose of the FormTagHelper class is to set the action
attribute of the form element using the application’s routing
configuration, ensuring that the form data is always sent to the
correct URL, even when the routing scheme changes. In Listing
24-5, I have used the asp-action and asp-controller attributes to
target the Create action method on the Home controller.

3
Using the Anti-forgery Feature
• Cross-site request forgery (CSRF) is a way to exploit a web application
to take advantage of the way that user requests are authenticated.
Most web applications—including those created using ASP.NET
Core—use cookies to identify which requests are related to a specific
session, with which a user identity is usually associated.
• CSRF—also known as session riding—is described in detail at
http://en.wikipedia.org/wiki/Crosssite_request_forgery but relies on
the user visiting a malicious web site after using your web application
and without explicitly ending their sessions by clicking a Logout
button. The application still regards the user’s session as being active,
and the cookie that the browser has stored has not yet expired.

4
• If a form element doesn’t contain an action attribute—because it
is being generated from the routing system with the asp-
controller and asp-acton attributes—then the FormTagHelper
class automatically enables the anti-CSRF feature, whereby a
security token is added to the form in a hidden input element to
the HTML sent to the client along with a cookie. The application
will process the request only if it contains both the cookie and the
hidden value from the form, which the malicious site cannot
access. Each request for the form generates a new and unique set
of security tokens.

5
Validating Anti-forgery Tokens

6
Enabling the Anti-CSRF Feature

You might also like