19
ASP.NET and ASP.NET Core

OVERVIEW OF WEB APPLICATIONS

A web application causes a web server to send graphics, HTML and/or JavaScript code to a client. That code is typically displayed in a web browser, for example Microsoft Edge, Chrome, or Firefox. When a user enters a web address (URL) into a browser and presses enter, an HTTP request is sent to the web server. The HTTP request can contain a filename like Default.aspx along with additional information such as cookies, the languages that the client supports, security tokens, and additional data belonging to the request. The web server then returns an HTTP response that contains HTML code. This code is interpreted by the web browser and can display, for example, text boxes, buttons, and lists to the user. If JavaScript is included in the HTTP response, that code will run on the client while loading or to perform validation prior to sending a further HTTP request. For example, the JavaScript might confirm that a value exists in a text box when a submit button is pressed. When the ASP.NET Web Form (ASPX) and ASP.NET Core applications are written later, take note of the ASP.NET Page object and its properties. In fact, two of the Page properties are Request and Response .

ASP.NET is a technology for dynamically creating web pages with server‐side code. These web pages can be developed with many similarities to client‐side Windows programs. Instead of dealing directly with the HTTP request and response and manually creating HTML code to send to the client, use ASP.NET controls such as TextBox , Label , ComboBox , and Calendar , which create HTML code. To create a TextBox server‐side control add the following to an ASP.NET Web Form (ASPX) file:

<asp:TextBox ID="player1TextBox" runat="server"/>

To achieve the same using razor syntax, which was introduced in Chapter 16 , use this syntax:

@Html.TextBox("player1TextBox")

In each case, when an HTTP request is made to the file containing those codes snippets, the code is executed, and an HTTP response is returned to the client containing an HTML representation of that control. Figure 19‐1 illustrates how a request flows from a browser to an IIS server and back.

Diagrammatic illustration showing how a request flows from a browser to an IIS server and back.

FIGURE 19‐1

WHICH ASP.NET TO USE AND WHY

After a solution architect or a programmer has decided that the best platform to run their program on is a web site, the next question is which flavor of ASP.NET to target. The first iteration of Microsoft’s web development platform was Active Server Pages or ASP. ASP used razor‐like syntax contained within an .asp file and often included an embedded VB COM instantiated using the Service.CreateObject() for initialization that provided the reference to the methods exposed via the API. Although ASP is still a supported technology, it would not be a recommended application type for the creation of any new web‐based program.

When the .NET Framework was created in the early 2000s the natural evolution of ASP was to utilize that framework when updating ASP, which was renamed to ASP.NET. The major change was the split between the presentation layer (.aspx file) and the business logic layer (aspx.cs or aspx.vb file), commonly referred to as a code‐behind . The supported languages in a code‐behind are C# and VB.NET, and the ASP.NET model was referred to as Web Forms. ASP.NET Web Forms were and continue to be a valid and fully supported technology for creating feature‐friendly and highly complex applications that target IIS and the Windows Server operating system. Over the many years of engineering and feature improvements, it became apparent that ASP.NET Web Forms was a little heavy. What “heavy” specifically means is described later, but this “heavy” stigma resulted in the development of a new ASP.NET flavor which is called ASP.NET MVC.

The MVC in ASP.NET MVC stands for Model‐View‐Controller. As mentioned previously, ASP.NET Web Forms split ASP code into two different layers: the presentation layer and the business logic layer. Now, MVC split this out into a third layer, the three layers being:

ASP.NET MVC was a logical iteration from the ASP.NET Web Form model, but be aware that ASP.NET MVC is significantly different in design, support concepts, and practices. Some programmers having an ASP.NET Web Form background might view the changes as a bit challenging from the beginning, but after digging in and using the model, clarity begins to take root. More on this in the sections of this chapter where each ASP.NET flavor is discussed in detail.

The most recent addition to the ASP.NET family is ASP.NET Core, which aligns with .NET Core like ASP.NET aligned with the .NET Framework. ASP.NET Core, like .NET Core, is an open source framework and platform which can target operating systems other than Microsoft Windows, such as, for example, Linux and MacOS. ASP.NET Core supports both Web Applications and Web Applications (Model‐View‐Controller) project types. Where ASP.NET Core Web Applications is similar to the ASP.NET Web Pages flavor and provides a simpler, less complex implementation for programmers of small web sites, ASP.NET Core Web Applications (MVC) provides full MVC capabilities for running web applications cross‐platform.

In summary, an ASP.NET Web API is like a .dll that exposes an API. There is no presentation layer, only the ability to call the exposed API method and passing the required parameters is available. The result of the API method call is a string of data, in the context of an ASP.NET Web API this string is in JSON format. The calling client then needs to parse and present the JSON data in a usable form. Now that the progression and evolution of the Microsoft web application frameworks are described, read on to learn why one should be used versus the other.

ASP.NET Web Forms

The reasons to choose ASP.NET Web Forms over the other frameworks are that Web Forms are:

  • Optimal for small to mid‐sized development teams and projects
  • Useful for web applications which need to maintain session and state over HTTP
  • Based on a very initiative set of request pipeline events

When compared to the other ASP.NET flavors, ASP.NET Web Forms is the best and simplest way to get a feature‐rich and highly‐performant web application developed and deployed rapidly. The separation between the presentation logic and the business logic align well with targeted skillsets of front‐end, user interface developers and coders. This is optimal because the team can have specialists working on the various aspects of the project in parallel.

ASP.NET Web Forms is often considered “heavy” due to a feature called viewstate . viewstate is one way in which state is maintained in an ASP.NET Web Form. For example, consider a web application that requires a series of page completions and submits to place an order. If a client hits the back button at some point in the process, viewstate is how the contents in the previous form are repopulated with the originally entered values. The issue with the viewstate feature is that it can be abused (i.e., overused), which results in a very large page size that moves back and forth between the client and the sever. As well, viewstate is enabled for the Page by default, instead of only on the web page controls that need to maintain state.

The best way to avoid problems with viewstate is to disable it at the Page level by setting the EnableViewState property to false . If you need to then maintain state on a TextBox , for example, use the following snippet to enable it specifically. Additionally, monitor the size of the .aspx files to make sure they are not getting too big.

<asp:TextBox EnableViewState="true" ID="Name"  runat="server"/>

It is not possible to maintain state without a session. Maintaining a session is a concept which comes from the era of client/server computing, where the connection between a computer and a server remained persistent. The HTTP protocol is synonymous with being stateless and is optimally suited for handling static (i.e., not dynamic) content.

ASP.NET Web Forms are dynamic because of the C# code in the code‐behind file (e.g., Default.aspx.cs ), which executes when the file is requested. The returned HTML delivered to the browser is most likely changed by the executing C# code based on the unique input from the client/user. The HTML can be different for each client based on the contents stored in the session cookie, as well. ASP.NET Web Form programmers store information in a session using the following syntax:

Session["username"] = TextBoxUID.Text;

The session variable with the name of <i>username</i> can then be accessed on subsequent HTTP requests using this code:

var username = Session["<i>username</i>"];

Lastly, events in the execution of an ASP.NET Web Forms request, such as BeginRequest , AuthenticateRequest , Init , Load , ProcessRequest , and EndRequest to name a few, are completely intuitive by name. That is important because when a programmer wants to take some special action toward authenticating a client or clean up any data before the request is completed, it’s easy to identify the location to place the code.

ASP.NET MVC

Some reasons for choosing ASP.NET MVC over other ASP.NET application types are that it is:

  • Well suited for larger, more complicated web applications
  • Tightly coupled with Entity Framework (EF) and model binding
  • Deeply integrated with test‐driven development (TDD)

Where ASP.NET Web Forms was split into two separate modules, as stated previously, ASP.NET MVC is split into three, a Model, a View, and a Controller (see Figure 19‐2 ). For the same reason that such separation helped ASP.NET Web Forms, it also helps ASP.NET MVC. The separation of the components allows larger teams to be split by specialization and work in parallel on the application, which results in a more rapid development cycle.

Diagrammatic illustration of an ASP.NET MVC split into three modules: a Model, a View, and a Controller.

FIGURE 19‐2

Entity Framework (EF) is an Object Relationship Model (ORM) technology, discussed in Chapter 23 , that is tightly coupled with the ASP.NET MVC architecture and model binding. ORMs, and therefore EF, give developers the power to design a database in an object‐oriented way. For example, if an ASP.NET MVC application is intended to store information about people, then a Person class, like the following can store and retrieve that information.

public class Person


{


  public string Name { get; set; }


  public int Age { get; set; }


}

Once the data model is designed, developers can deploy the model to a database (like SQL Server) and the data structure. The database tables and primary and foreign keys are generated using the description in the C# classes. When an ASP.NET MVC application is created in Visual Studio, part of the default solution is a folder named Models . This is the location where C# class representations of database tables reside. These classes are used to store the data from the database in memory for modification by the controller updating from the view. Each of which also have a folder in a default ASP.NET MVC application named Controllers and Views .

The controller is the location where a developer places the code to create, read, update, or delete contents of a database via EF logic through a bound Model object like a Person . The controller is also where any business logic, authentication, or any other activity the application needs is performed. The view is the presentation layer where the output of the actions triggered from the client and executed in the controller using an object‐oriented model is presented back to the client.

ASP.NET MVC is deeply integrated with test‐driven development techniques and is much simpler to unit test when compared to ASP.NET Web Forms. As shown in Figure 19‐3 , when you create an ASP.NET application, there is a check box to select that results in the creation of a second project dedicated to unit testing the program.

Screenshot illustration of a check box to select, which results in the creation of a second project when creating an ASP.NET application.

FIGURE 19‐3

By placing test code in the Tests project, dependencies such as IIS, databases, and external classes can be abstracted away from the test cases. This is an important and very beneficial feature as data is often different between production instances, and the build of a server running IIS may also deliver inconsistent behavior between production and testing environments. Removing these dependencies—by testing only the logic within the controller, regardless of the dependency state—improves the speed and efficiency of testing. The reason is that instead of keeping all the dependencies in a valid and stable testing state, which can be very time consuming, a developer can focus only on making sure the testing scenarios complete successfully.

ASP.NET MVC utilizes extension‐less URLs : No specific filename is placed into the request. .aspx files are requested for ASP.NET Web Form applications, but this is not the case for ASP.NET MVC. ASP.NET MVC uses the concept of routes or routing where URL segments instead of a filename are used to route the request to the correct controller and view. For example, a request to /Home/About would execute the About() method in a controller named HomeController , which is found in the Controllers folder. The results of the About() method are presented to the client, using the view named About.cshtml located in the Views\Home directory.

ASP.NET Web API

The benefits of choosing an ASP.NET Web API are similar to those for an ASP.NET MVC application in that the application type is tightly coupled with EF, deeply integrated into the TDD concepts, and it is well suited for large and complicated web applications. The primary difference is that there is no View component or Views folder in a ASP.NET Web API Visual Studio project. This makes perfect sense simply based on the API concept, described in Chapter 17 , where a client calls a method, exposed by the API, that returns some data. The client is responsible for consuming, reacting to, and/or presenting the result of the API, which is typically in the JSON format.

ASP.NET Core

The benefits of .NET Core and .NET Standard are discussed in Chapter 18 . The advantages realized with .NET Core exist within the ASP.NET Core application type as well. The following are examples of the benefits:

  • ASP.NET Core run across platforms.
  • ASP.NET Core is not dependent on IIS.
  • ASP.NET Core does not rely on the full .NET Framework.
  • ASP.NET Core is optimized for the cloud and is more performant.

Like .NET Core, ASP.NET Core can run on operating systems other than Microsoft Windows such as MacOS and Linux. Historically, when talking about any ASP.NET application type it was doubtlessly tied to Internet Information Services (IIS). ASP.NET Core includes a new web server called Kestrel which is described in more detail in the “Creating ASP.NET Core Web Applications” section in this chapter. ASP.NET Core can run on IIS as a reverse proxy server or in a self‐contained container running only Kestrel.

ASP.NET Core does not need nor rely on the full .NET Framework library. Instead, like .NET Core, only the assemblies required to perform the function of the program are included in the application deployment package. The modularized, highly performant, and self‐contained application package is what gets deployed to a server or cloud platform for execution and consumption.

Due to the optimizations in size and code execution paths with ASP.NET Core on Kestrel, performance when compared to ASP.NET 4.6 Web Forms experiences an increase of 5.5x in its ability to handle requests per second. When compared to Node.js, ASP.NET Core on Kestrel exceeds the performance by a factor of three, as described in Table 19‐1 .

TABLE 19-1 : Baseline ASP.NET Core on Kestrel performance

STACK REQUESTS PER SECOND (RPS)
ASP.NET Web Forms 4.6 ~57,000
ASP.NET Core on Kestrel ~310,000
Node.js ~105,000

The RPS performance tests were performed on the same operating system, Windows Server 2012 R2, with the same amount of RAM, CPU speed/type, and network interface card. Therefore, the performance is due specifically to the optimizations and execution efficiencies existing in the application type.

ASP.NET Web Site versus ASP.NET Web Application Project Types

As shown in Figure 19‐4 , a new ASP.NET web application comes in two types: Projects and Web Sites.

Screenshot illustration of a new ASP.NET web application that comes in two types: Projects and Web Sites.

FIGURE 19‐4

The differences between them are shown in Table 19‐2 .

TABLE 19-2 : Differences between Projects and Web Sites

DIFFERENCE PROJECTS WEB SITES
File Structure C# project has a .csproj file which contains a list of files and assembly references required to run the program. There is no .csproj file for Web Sites created in C#. All files existing in the directory structure are included in the site.
Compiling The code‐behind files are compiled into a single assembly (.dll). Source code is compiled dynamically when first requested. Usually results in multiple assemblies (.dll).
Deployment The assembly (.dll), .aspx and .ascx files are deployed to the web server where the application is consumed. A copy of the web application source is deployed to the web server (.aspx, .ascx and aspx.cs).

File Structure

A .csproj (project file) for ASP.NET Projects provides the ability to remove from the project a file that will not be included in the deployment, but also will not be removed permanently. The file is excluded from the project but not deleted. This is helpful if there is a need to make a deployment but some of the files are not ready for it. Additionally, as you learned in the previous chapter, the project file is used to store information about a .NET Standard class that is used to create a NuGet package. Where there is no .csproj file, in the Web Sites context, all files within the directory structure of the site are considered part of the solution.

Compiling

Having the web application project compiled before deployment saves the time that would otherwise be spent compiling the .aspx file and its code‐behind on the first request after deployment. Although web sites can be precompiled using NGEN, that kind of pre‐deployment activity is much more complicated than simply manually making the first request so that the ASP.NET files are compiled by the ASP.NET Runtime.

When the compiled assembly or an ASP.NET Project is loaded into memory, the entire web application consumes the memory. On the other hand, only the files that are part of a Web Site that gets requested are compiled and loaded into memory. Therefore, a project where only a small number of the pages are actually ever used would consume more memory than a web site over time, because, as previously stated, only files that are requested get compiled and loaded into memory. This is an important concept when customers pay for resource consumption on a cloud platform.

Deployment

When a Web Site is deployed, the source code in the code‐behind (.aspx.cs ) is deployed as plain text and is human‐readable. So long as the location where the web site is deployed is secure, that is not a problem, but still some developers or businesses might not want that. Instead, with a project, no human‐readable code is deployed to the server as it is all compiled into an assembly (.dll ).

Additionally, to make a change to the project after the compiled assembly (.dll ) that is part of the ASP.NET web application project is loaded into the ASP.NET Runtime, the ASP.NET Runtime process must be stopped and unloaded from memory for the change to become available to clients using the web site. If the process has a handle on the assembly, it cannot be changed and therefore must be stopped to release the handle. This is not the case with Web Sites where the .aspx.cs or .aspx files can be updated without stopping the ASP.NET Runtime and are compiled and loaded into memory the next time there is a request to them.

Now you know the differences between the numerous ASP.NET web application flavors as well as many of the differences between Projects and Web Sites. Read on for a deeper look into ASP.NET Web Forms and ASP.NET Core.

USING ASP.NET WEB FORMS

In this section a few important ASP.NET Web Form concepts are discussed in more detail. Each of the ASP.NET application flavors have aspects that make them unique (the specifics were discussed previously). After reading this section, you will have a solid understanding of the of the following ASP.NET Web Form features:

Server Controls

In this section, you will learn about the server controls provided by the ASP.NET page framework. These controls are designed to provide a structured, event‐driven, object‐oriented model for programming web applications. Table 19‐3 lists some of the principal web server controls available with ASP.NET, and the HTML code returned by these controls.

TABLE 19-3 : Examples of ASP.NET Server Controls

CONTROL HTML DESCRIPTION
Label <span> Returns a span element containing text.
TextBox <input type=text> Returns HTML <input type=text> whereby the user can enter some values. You can write a server‐side event handler when the text changes.
Button <input type=submit> Sends form values to the server.
HyperLink <a> Creates a simple anchor tag referencing a web page.
DropDownList <select> Creates a select tag whereby the user sees one item and can select one of multiple items by clicking on the drop‐down list.
CheckBox <input type=checkbox> Returns an input element of type check box to show a button that can be selected or deselected. Instead of using the CheckBox , you can use a CheckBoxList , which creates a table consisting of multiple check box elements.
RadioButton <input type=radio> Returns an input element of type radio . With a radio button, just one button of a group can be selected. Similar to the CheckBoxList , RadioButtonList provides a list of buttons.
Image <img src= ””> Returns an img tag to display a GIF or JPG file on the client.

There are many additional controls not shown in this table. However, these controls all have in common an ability to fire off events invoked by the user, either automatically or as part of the page event lifecycle. These events execute server‐side event handlers. You will find ASP.NET applications are largely structured based on this event‐driven model.

Input Validation

When users enter data, it should be checked for validity. The check can happen on both the client and on the server. You can check the data on the client using JavaScript. However, if the data is checked on the client using JavaScript, it should also be checked on the server, because you can never fully trust the client. It is possible to disable JavaScript in the browser, and hackers can use different JavaScript functions that accept incorrect input. Checking the data on the client leads to better performance, as no round‐trips occur to the server until the data is validated on the client.

With ASP.NET it is not necessary to write the validation functions yourself. Many validation controls exist that create both client‐ and server‐side validation. The following example shows the RequiredFieldValidator validation control that is associated with the text box player1TextBox . All validator controls have the properties ErrorMessage and ControlToValidate in common. If the input is not correct, then ErrorMessage defines the message that is displayed. By default, the error message is displayed where the validator control is positioned. The property ControlToValidate defines the control where the input is checked.

<asp:TextBox ID="player1TextBox" runat="server"></asp:TextBox>


<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"


    ErrorMessage="Enter a name for player 1" ControlToValidate="player1TextBox">


</asp:RequiredFieldValidator>

Table 19‐4 lists and describes all the validation controls.

TABLE 19-4 : Examples of ASP.NET Validation Controls

CONTROL DESCRIPTION
RequiredFieldValidator Specifies that input is required with the control that is validated. If the control to validate has an initial value set, which the user has to change, you can set this initial value with the InitialValue property of the validator control.
RangeValidator Defines a minimum and maximum value that the user is allowed to enter. The specific properties of the control are MinimumValue and MaximumValue .
CompareValidator Compares multiple values (such as passwords). Not only does this validator support comparing two values for equality, additional options can be set with the Operator property. The Operator property is of type ValidationCompareOperator , which defines enumeration values such as Equal , NotEqual , GreaterThan , and DataTypeCheck . Using DataTypeCheck , the input value can be checked to determine whether it is of a specific data type, for example, correct date input.

State Management

The HTTP protocol is stateless. The connection that is initiated from the client to the server is closed after every request. However, normally it is necessary to remember some client information from one page to the other. There are several ways to accomplish this.

The main difference among the various ways to keep state is whether the state is stored on the client or on the server. Table 19‐5 shows an overview of state management techniques and how long the state can be valid.

TABLE 19-5 : ASP.NET Web Forms State Management Techniques

STATE TYPE CLIENT OR SERVER RESOURCE TIME VALID
View State Client Within a single page only.
Cookie Client Temporary cookies are deleted when the browser is closed; permanent cookies are stored on the disk of the client system.
Session Server Session state is associated with a browser session. The session is invalidated with a timeout (by default, 20 minutes).
Application Server Application state is shared among all clients. This state is valid until the server restarts.
Cache Server Similar to application state, cache is shared. Developers have control over when the cache can be invalidated.

Authentication and Authorization

To secure the website, authentication is used to verify that the user has a valid logon, and authorization confirms that the user who was authenticated can use the resource. Commonly used authentication techniques for web applications are Forms and Windows authentication. Windows Authentication makes use of Windows accounts and IIS to authenticate users while Forms requires a database that contains user access information.

ASP.NET has many classes for user authentication. With ASP.NET, many security controls, such as Login and PasswordRecovery , are available. These controls make use of the Membership API. With the Membership API, it is possible to create and delete users, validate logon information, or get information about currently logged‐in users. The Membership API makes use of a membership provider. Since ASP.NET 4.5, different providers exist to access users in an Access database, a SQL Server database, or the Active Directory. It is also possible to create a custom provider that accesses an XML file or any custom store.

In the following Try It Out, you will create an ASP.NET Web Forms application that deals a hand of cards to two players.

ASP.NET Web Forms are still a very valid option for rapidly creating fully functional, resource‐rich web‐based applications. This flavor of ASP.NET application uses the full version of the .NET Framework, which means the application will run solely on the Microsoft Windows platform. If the web application needs to run on multiple operating systems, then ASP.NET Core (discussed in the next section) might be a better choice.

CREATING ASP.NET CORE WEB APPLICATIONS

This section discusses numerous ASP.NET Core concepts. The most important concept to take away from the section is that ASP.NET Core can be run cross‐platform. Like .NET Core applications, ASP.NET Core web sites can run on Linux and MacOS in addition to Microsoft Windows. Therefore, if the web application needs to run cross‐platform, this is the ASP.NET flavor to develop in. If, however, the web application is targeted to run only on Microsoft Windows, you should consider using either ASP.NET Web Forms or ASP.NET MVC. At the time of writing, ASP.NET Core is the newest flavor of ASP.NET, but not all capabilities are included in the binary yet. This will change in the future.

You will learn about the following ASP.NET Core specifics in this section:

IIS and Kestrel

Up to now, when developers spoke about an ASP.NET flavor, it was understood that the web application would run on a Microsoft Windows server with Internet Information Services (IIS), a Microsoft‐developed web server that responds to HTTP and HTTPS requests from clients. However, because IIS won’t run on Linux or MacOS, there needs to be a way for IIS to send requests to a web server that can run on those operating systems. The answer is to use Kestrel, a new cross‐platform web server included with ASP.NET Core projects.

As shown in Figure 19‐8 , when Kestrel is configured to run with IIS, the clients’ HTTP request is simply forwarded to the Kestrel web server. Kestrel then interacts with the ASP.NET Core source code by passing the HttpContext class, which contains the HTTP‐specific information about the HTTP request (for example, session management information, query string, culture information, client certificates, and much, much more).

Diagrammatic illustration showing that when Kestrel is configured to run with IIS, the clients&#8217; HTTP request is simply forwarded to the Kestrel web server.

FIGURE 19‐8

In addition to IIS, Apache and Nginx are functional web servers which run only on their targeted operating system like Windows, Linux or MacOS. ASP.NET Core can run without any operating system‐specific web server, as Kestrel is a web server. Running in this manner is commonly referred to as self‐hosting in that the web application and the components required to operate are enclosed within a dedicated container. Having the web application bundled together in this manner makes it easily deployable using, for example, XCOPY, and portability is a fundamental characteristic of a cloud optimized program, as described in Chapter 16 .

Razor Syntax

Instead of Server Controls, a basic design principle of ASP.NET Web Forms, use the HTML rendering feature when creating Razor pages for an ASP.NET Core application. When referencing variables in a page, historically the markup syntax was <%= %> , which is five characters. The improvement with Razor is that the @ sign is used to denote the starting point of code or for setting a reference to a variable. For example, @Html.Hidden is the way a hidden field is added to a Razor page. The Html object provides the reference to the constructors, properties, fields, and methods of the System.Web.Mvc.HtmlHelper class. Table 19‐6 lists a few HtmlHelper methods accessible from a Razor web page. The HTML output is very similar to the ASP.NET Web Forms Server Control output.

TABLE 19-6 : Examples of Razor HtmlHelper methods

CONTROL HTML DESCRIPTION
Html.Label <label> Returns a label element containing text.
Html.TextBox <input type=text> Returns HTML <input type=text> whereby the user can enter some values.
Html.ActionLink <a href> Creates a simple anchor tag referencing a web page.
Html.DropDownList <select> Creates a select tag whereby the user sees one item and can select one of multiple items by clicking on the drop‐down list.
Html.CheckBox <input type=checkbox> Returns an input element of type check box to show a button that can be selected or deselected.
Html.RadioButton <input type=radio> Returns an input element of type radio . With a radio button, just one button of a group can be selected.

There are many other HtmlHelper methods that are not included in this table.

Input Validation

Validation for an ASP.NET Core application is configured using validation attributes existing within the System.ComponentModel.DataAnnotations namespace. The validators are configured in the class definition for a specific model.

public class Player


{


    [StringLength(20, MinimumLength = 3)]


    [Required]


    public string <b>Name</b> { get; set; }


}

When a request is made to the page that binds with the defined Player model, the ASP.NET Core runtime generates jQuery client‐side validation syntax. Then, if a user attempts to submit a form without a value for Name , validation happens on the client and an error is rendered.

Table 19‐7 lists and describes some ASP.NET Core data annotation validation attributes.

TABLE 19-7 : Examples of ASP.NET Core Validation Attributes

CONTROL DESCRIPTION
Required Indicates that the property is required.
StringLength Defines a maximum and an optional minimum value that the user must.
Range For a numeric field, maximum and minimum values can be set.
EmailAddress Confirms that the entered value is an email address.
DataType Confirms that the entered value is a specific type like Date or Currency .
RegularExpression Confirms that the entered value matches regular expression syntax.

State Management

As previously mentioned, the HTTP protocol is stateless, which means that once the request has been successfully responded to by the server, no information is stored about the client that made the request. The connection is closed and forgotten after every request. However, it does often happen that some information about the client needs to be persisted and reused when managing multiple requests from a client. As is true with other ASP.NET flavors, there are several ways to implement the management of state‐full information when using HTTP. Table 19‐8 shows an overview of state management techniques and how long the state can be valid.

TABLE 19-8 : ASP.NET Core State Management Techniques

STATE TYPE CLIENT OR SERVER RESOURCE TIME VALID
TempData Server Removed once the data is read by the application.
Query strings Both Passed between client and server as URL elements and are accessible only during a single request.
Cookie Client Temporary cookies are deleted when the browser is closed; permanent cookies are stored on the disk of the client system.
HttpContext.Items Both Passed between client and server, stored in the HttpContext object, and accessible only during a single request.
Cache Server Similar to application state, cache is shared. However, when the cache should be invalidated, there’s much better control.
Session Server Session state is associated with a browser session. The session is invalidated with a configurable timeout setting.
Application Server Application state is shared among all clients. This state is valid until the server restarts.

Authentication and Authorization

Since ASP.NET Core is not focused on a single operating system, the authentication and authorization protocols must also work cross‐platform. The most popular open source authentication providers are OWIN and OAuth. OWIN, which stands for Open Web Interface for .NET, isn’t an authentication provider per se; however, it is commonly associated with Katana, which is. OWIN is a specification that details how web servers and web applications should be decoupled from each other. OWIN removes the dependency of ASP.NET Core from IIS and helps make the self‐hosting concept via Kestrel a reality. The Katana NuGet package contains the libraries necessary for implementing the many types of authentication like Windows and Forms, for example.

OAuth is an interface exposed by companies like Microsoft, Facebook, Twitter, Google and others for web applications to authenticate against. It is common for applications running on a mobile device or in a browser to prompt client to use Facebook or Microsoft credentials to access the web site. In those cases, OAuth is the protocol being used. The classes and methods for implementing OAuth into an ASP.NET Core web application are found in the AspNet.Security.OAuth.Providers namespace.

Authentication is the process of confirming that individuals are really who they say they are. Usually when someone creates a new account, it’s linked to an email address and a password. A verification email is sent to the provided email and once clicked, the registration is completed. Using that email and password from then on to access a resource validates that it really is the one who created the account. The other portion of the process is authorization. Authorization is the process of defining what features or content the authorized person has access to. This is commonly referred to as claims .

In the simplest form, some source code checks for the existence of a claim, for example to a DealCard() method, and if the claim exists, the method can be called from the requesting card dealer.

policy.RequireClaim("DealerID");

Claims can also be represented by name‐value pairs that provide more granular access to a resource.

policy.RequireClaim("DealerID", "1", "2", "3", "4", "5"));

This shows that the DealCard() is only available for a card dealer with a DealerID equal to 1, 2, 3, 4, or 5.

Dependency Injection

Dependency Injection (DI) is a very advanced topic but as it is a fundamental concept on which ASP.NET Core is built, so it will be touched on here. The basic point to understand when it comes to DI is the avoidance of the new keyword.

Player[] players = <b>new</b> Player[2];

The reason for avoiding new is that it permanently binds the program to the class it refers to. There are cases where using new is acceptable when the likelihood that the class will need to be modified is very slim, in which case using the keyword is a design decision. The alternative is the implementation of an interface, which was discussed in Chapters 9 , 10 , and 12 . An interface loosely couples or decouples the consumer from the provider, where the program is the consumer and the class is the provider. As seen in the following code snippet, a Player is created without using the new keyword.

public interface ICardGameClient


{


    void Player(string Name);


}


public class PlaySomeCards


{


    private readonly ICardGameClient _cardGameClient;


    public PlaySomeCards(ICardGameClient cardGameClient)


    {


        _cardGameClient = cardGameClient;


    }


    public PlayHand


    {


        _cardGameClient.Player("Benjamin");


    }


}

Dependency Injection takes it one step further by using what is known as a factory or container. ASP.NET Core supports DI by default and is configured into the Startup.cs file, which is created with an ASP.NET Core web application. This file contains a method named ConfigureServices() and is the place where the providers are configured.

public void ConfigurServices(IServiceCollection services)


{


    services.AddMvc();


    services.AddDbContext<<b><i>className</i></b>>(options => …


    services.AddIdentity<<b><i>className1</i></b>,<b><i>className2</i></b>>()…





}

The configured service providers contained in the ConfigureServices() method provide the className when it is requested from the code running within the program.

In the following Try It Out, you will create a Razor Page in ASP.NET Core that deals a hand of cards to two players.

image WHAT YOU LEARNED IN THIS CHAPTER

TOPIC KEY CONCEPTS
ASP.NET flavors There are numerous ASP.NET application types, each have specific cases and benefits for use.
Projects vs. Web Sites Projects are compiled into a .dll and deployed while Web Sites deploy the source code and are compiled when requested for the first time.
Server controls and the HtmlHelper Web Server Controls are server‐side controls that generate HTML code for ASP.NET Web Forms applications. The HtmlHelper class provides the means to create objects such as Label , Textbox , and so on with Razor pages.
Verifying user input with validation controls and Data Annotations ASP.NET offers several validation controls that can easily be used to validate user input on both the client and server sides. Validation on the client is done for performance reasons, but because the web client can never be trusted, validation must happen on the server as well.
State management With web applications it is necessary to think about where to store state. State can be stored on the client with cookies or view state, and on the server with session, cache, and application objects.
Authentication and Authorization Authentication is the process that determines whether clients really are who they say they are. Authorization provides access to features and services the authenticated client has access to.
Kestrel Kestrel is a new web server that can self‐host ASP.NET Core web applications and can run cross‐platform.
Dependency Injection (DI) DI decouples consumers and providers.