Discover millions of ebooks, audiobooks, and so much more with a free trial

Only $11.99/month after trial. Cancel anytime.

Beginning Database Programming Using ASP.NET Core 3: With MVC, Razor Pages, Web API, jQuery, Angular, SQL Server, and NoSQL
Beginning Database Programming Using ASP.NET Core 3: With MVC, Razor Pages, Web API, jQuery, Angular, SQL Server, and NoSQL
Beginning Database Programming Using ASP.NET Core 3: With MVC, Razor Pages, Web API, jQuery, Angular, SQL Server, and NoSQL
Ebook730 pages5 hours

Beginning Database Programming Using ASP.NET Core 3: With MVC, Razor Pages, Web API, jQuery, Angular, SQL Server, and NoSQL

Rating: 0 out of 5 stars

()

Read preview

About this ebook

Hit the ground running with this book to quickly learn the fundamentals of HTML form processing, user authentication, and database CRUD (Create, Read, Update, and Delete) operations using the ASP.NET Core family of technologies. You will utilize cutting-edge and popular technology options from both the server side and client side to help you achieve your web application goals as quickly as possible.

Developers who want to learn ASP.NET Core and complementary technologies are often overwhelmed by the large number of options involved in building modern web applications. This book introduces you to the most popular options so that you can confidently begin working on projects in no time. You will learn by example, building a sample application that demonstrates how the same application can be built using different options. This experiential approach will give you the basic skills and knowledge to understand how the options work together so that you can make an informed decision about the available choices, their trade-offs, and code level comparison. After reading this book, you will be able to choose your selected learning path.


What You Will Learn

  • Develop data entry forms in ASP.NET Core, complete with validations and processing
  • Perform CRUD operations using server-side options: ASP.NET Core MVC, Razor Pages, Web APIs, and Blazor
  • Perform CRUD operations using client-side options: jQuery and Angular
  • Secure web applications using ASP.NET Core Identity, cookie authentication, and JWT authentication
  • Use RDBMS and NoSQL data stores: SQL Server, Azure SQL Database, Azure Cosmos DB, and MongoDB for CRUD operations
  • Deploy ASP.NET Core web applications to IIS and Azure App Service


Who This Book Is For
Developers who possess a basic understanding of ASP.NET and how web applications work. Some experience with Visual Studio 2017 or higher, C#, and JavaScript is helpful.

LanguageEnglish
PublisherApress
Release dateDec 11, 2019
ISBN9781484255094
Beginning Database Programming Using ASP.NET Core 3: With MVC, Razor Pages, Web API, jQuery, Angular, SQL Server, and NoSQL

Related to Beginning Database Programming Using ASP.NET Core 3

Related ebooks

Programming For You

View More

Related articles

Reviews for Beginning Database Programming Using ASP.NET Core 3

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Beginning Database Programming Using ASP.NET Core 3 - Bipin Joshi

    © Bipin Joshi 2019

    B. JoshiBeginning Database Programming Using ASP.NET Core 3 https://doi.org/10.1007/978-1-4842-5509-4_1

    1. Introduction to ASP.NET Core

    Bipin Joshi¹ 

    (1)

    Thane, India

    This chapter introduces you to the basics of ASP.NET Core. It discusses the main development options available in ASP.NET Core, namely, MVC, Razor Pages, and Web API. Since you are going to work extensively with ASP.NET Core projects in the later chapters, it is worthwhile to learn how to create an ASP.NET Core web application using the Visual Studio IDE. To that end, this chapter helps you to

    Understand main development options available in ASP.NET Core.

    Create an ASP.NET Core MVC application.

    Create an ASP.NET Core Razor Pages application.

    Create an ASP.NET Core Web API application.

    Install the Northwind sample database.

    Overview of ASP.NET Core

    ASP.NET Core is a framework for building modern web applications and services. It’s part of .NET Core and is a cross-platform and open source framework. This means you can develop and deploy your web applications targeting all the popular operating systems such as Windows, Linux, and macOS.

    ASP.NET Core is a redesigned and rewritten framework for building modern web applications. Although we won’t discuss each and every feature of the framework here, some of its important technical features are listed as follows:

    Cross-platform framework. You can develop and run web applications on Windows, Linux, and macOS.

    Open source with a lot of community involvement.

    Built-in dependency injection (DI) framework.

    ASP.NET Core includes a built-in web server called Kestrel. You can use Kestrel by itself or host your web applications under IIS, Nginx, or Apache.

    Multiple development options for UI including MVC, Razor Pages, and Blazor. (Of course, you can also use client-side JavaScript frameworks to develop the front-end.)

    Unified programming model for MVC web applications and Web APIs.

    High-performance modular request pipeline suitable for modern, cloud-optimized applications.

    Figure 1-1 shows the layers of ASP.NET Core.

    ../images/481875_1_En_1_Chapter/481875_1_En_1_Fig1_HTML.jpg

    Figure 1-1

    Layers of .NET Core and ASP.NET Core

    As you can see from Figure 1-1, the bottommost layer is the operating system. Because .NET Core is a cross-platform framework, this could be Windows, Linux, or macOS. Your web application code is going to be the same regardless of the underlying operating system.

    To develop and run .NET Core applications, you must have language compilers and other necessary runtime components. They are installed when you install .NET Core on the machine.

    The next layer primarily consists of the .NET Core libraries and framework-level services. These libraries provide you several features including data types and file IO. ASP.NET Core makes use of the .NET Core libraries and hence is shown sitting on top of this layer.

    ASP.NET Core offers three main development options, namely, ASP.NET Core MVC, ASP.NET Core Razor Pages, and ASP.NET Core Web APIs. These options make the top layer of the diagram.

    ASP.NET Core is built considering modularity. Most of the ASP.NET Core applications (MVC/Razor Pages/Web APIs) make use of functionality that resides in NuGet packages.

    From the preceding discussion, you know that there are three primary development options – MVC, Razor Pages, and Web APIs. Let’s discuss each of them briefly before we go into the code-level details.

    Note

    You can also use Blazor to build interactive rich client-side UI using C#, HTML, and CSS. However, Blazor is a relatively new addition to the ASP.NET Core family and hence is not discussed in this chapter. You learn more about Blazor in Chapter 8.

    ASP.NET Core MVC

    ASP.NET Core MVC allows you to build web applications using the Model-View-Controller (MVC) pattern. Although detailed discussion of the MVC pattern is beyond the scope of this book, a brief discussion of MVC as applicable to ASP.NET Core follows.

    The responsibility of a web application built using ASP.NET Core MVC is divided into three components: model, view, and controller. Model represents the application’s data and could be anything from a primitive type to a complex object. View houses the application’s user interface (UI) and usually displays data held by the model. View also accepts user input and commands. Controller mediates between a model and a view. Its job is to prepare the model required for a view and also to act upon the user input and commands as captured by the view. It also decides the program flow by deciding which model and view to send next to the user. Thus, a controller might need to deal with many models and many views. An end user never deals with a model and a view directly; rather, it invokes the controller.

    Figure 1-2 shows the model, view, and controller relationship.

    ../images/481875_1_En_1_Chapter/481875_1_En_1_Fig2_HTML.jpg

    Figure 1-2

    MVC pattern as applied to ASP.NET Core MVC

    As far as ASP.NET Core MVC is concerned, a model typically takes the form of a C# object(s) and often holds data from some data store such as SQL Server. A view physically exists as a .cshtml file and primarily contains markup and Razor code. A controller is a C# class and typically contains one or more methods called actions. The job of a controller as discussed earlier is accomplished by its actions. The end user invokes the controller to get some job done.

    ASP.NET Core MVC is a good development choice when your program flow is complex and involves multiple models and views. It’s also a preferred development option for Ajax-based scenarios and Single Page Applications (SPAs).

    ASP.NET Core Razor Pages

    ASP.NET Core Razor Pages allows you to build web applications that use a Model-View-ViewModel (MVVM)-like pattern . The Model-View-ViewModel pattern splits the application functionality into three components: model, view, and ViewModel. The striking difference between MVC and MVVM is the absence of a separate controller class.

    In MVVM, the model and the view have the same responsibilities as in the MVC pattern. The ViewModel is closely related to a view and is responsible for view-specific things such as data binding, UI event handling, and UI notifications. It encapsulates view-specific data and behavior. It also updates the underlying data model whenever necessary.

    Figure 1-3 shows MVVM as applicable to Razor Pages.

    ../images/481875_1_En_1_Chapter/481875_1_En_1_Fig3_HTML.jpg

    Figure 1-3

    MVVM pattern as applied to ASP.NET Core Razor Pages

    As far as ASP.NET Core Razor Pages is concerned, the view resides in a .cshtml file just like that of an MVC application. For each view, there is a PageModel (ViewModel from MVVM) C# class that houses bindable properties and form processing actions called handlers. The PageModel class also deals with the data model to update or fetch application data.

    Razor Pages is the preferred development option for page-focused scenarios with a simple program flow. The lack of a controller class also makes their code organization simpler.

    ASP.NET Core Web API

    ASP.NET Core Web APIs make use of the same controller-based programming model as used by MVC applications. However, they don’t have any views. Web APIs expose certain functionality using REST (REpresentational State Transfer) guidelines. Typically, a Web API consists of a controller that houses five actions. These actions deal with HTTP verbs, namely, GET, POST, PUT, and DELETE. The Web API actions contain processing that you want to execute when the Web API is invoked using a particular HTTP verb.

    Once a Web API is ready, it’s hosted on a server so that client applications can consume it. The clients could be any type of application such as a JavaScript application, a server-side web application, or even a desktop application.

    Figure 1-4 shows the arrangement of a Web API.

    ../images/481875_1_En_1_Chapter/481875_1_En_1_Fig4_HTML.jpg

    Figure 1-4

    Web API implementing REST guidelines

    As you can see from Figure 1-4, a Web API is a controller named CustomerApiController that contains five actions – Select(), SelectByID(), Insert(), Update(), and Delete(). The action names could be anything, but they are mapped to an HTTP verb. For example, the Select() action is mapped to deal with GET verb, the Insert() action is mapped to deal with POST verb, and so on.

    Also notice the parameters of these actions. Two variations of Select() are possible – one that accepts no parameters and the other that accepts an ID of a resource as its parameter. The former variation is intended to retrieve information about multiple resources, whereas the latter is intended to retrieve information about a particular resource matching the specified ID. The Insert() action accepts an object that indicates a new resource to be created on the server. The Update() action accepts an ID of a resource to be updated and an object containing modified values of that resource. The Delete() action accepts an ID of a resource to be deleted.

    The Web API is made available at a well-known URL (http://localhost/api/customer in this example). The client application then makes HTTP requests to the Web API in an attempt to invoke the desired functionality.

    Web APIs are quite common wherever functionality is to be exposed through a service. This includes Ajax-based scenarios, Single Page Applications (SPA), and also the service layer.

    Now that you know the main development options in ASP.NET Core, let’s build a simple Hello World application using each of them.

    Note

    If you are already comfortable working with Visual Studio IDE and ASP.NET Core projects, you may skip to Chapter 2. If you are new to ASP.NET Core development or have recently started playing with it, you might want to go through the following sections to get an idea of overall project structure and code organization.

    Creating an ASP.NET Core MVC Project

    In this section, you will create a Hello World project using ASP.NET Core MVC. The application you develop will output a message – Hello World! – in the browser and will also allow you to specify a custom message. Figure 1-5 shows the main page of the application.

    ../images/481875_1_En_1_Chapter/481875_1_En_1_Fig5_HTML.jpg

    Figure 1-5

    Main page of the Hello World application

    As you can see, the page displays a Hello World! message in the heading, but also allows you to enter a different message in a textbox. Upon clicking the Submit button, the Hello World! will be replaced by the new message you specify. This is shown in Figure 1-6 where the message is changed to Hello Universe!.

    ../images/481875_1_En_1_Chapter/481875_1_En_1_Fig6_HTML.jpg

    Figure 1-6

    Message changed to Hello Universe!

    To begin developing this application, open Visual Studio and click the Create a new project option from the start window (Figure 1-7).

    ../images/481875_1_En_1_Chapter/481875_1_En_1_Fig7_HTML.jpg

    Figure 1-7

    Creating a new project

    Doing so will open another dialog wherein you can select a project template for your new project. This dialog is shown in Figure 1-8.

    ../images/481875_1_En_1_Chapter/481875_1_En_1_Fig8_HTML.jpg

    Figure 1-8

    Selecting a project template

    Select ASP.NET Core Web Application in this dialog and click the Next button. You will be asked to enter a project name and its location (Figure 1-9).

    ../images/481875_1_En_1_Chapter/481875_1_En_1_Fig9_HTML.jpg

    Figure 1-9

    Specifying a project name and location

    Specify those details and click the Create button. As the final step, you need to pick an ASP.NET Core project template (Figure 1-10).

    ../images/481875_1_En_1_Chapter/481875_1_En_1_Fig10_HTML.jpg

    Figure 1-10

    Picking an ASP.NET Core project template

    Here, you will have many project templates such as Empty, API, Web Application, and Web Application (Model-View-Controller). You can also select the .NET framework type – .NET Core or .NET Framework – and the ASP.NET Core version from the dropdown lists at the top. By default, .NET Core and ASP.NET Core 3.0 will be selected in these dropdowns. Keep that selection unchanged. Select the Empty project template from the list.

    The Configure for HTTPS checkbox under the Advanced section is checked by default. If this checkbox is checked, the project is configured to use an HTTPS self-signed certificate. Since the certificate is self-signed, your browser might show you a security warning when you run such application. And you will need to configure your browser to trust this certificate (simply follow the browser’s instructions). If you uncheck this checkbox, the project uses HTTP. Projects that you create in this book can work with any scheme (HTTP or HTTPS), but in most of the real-world cases, you would prefer HTTPS for security reasons. Now click Create to create the project.

    Note

    While we could have selected the Web Application (Model-View-Controller) template for our project, we chose not to, instead selecting the Empty project template. This selection will give you the opportunity to learn how to add all the pieces that go in an application yourself, rather than relying on pieces added by the project template.

    Once the empty project gets created, add three folders under the project root – Models, Views, and Controllers – by right-clicking the project and then selecting the Add ➤ New Folder shortcut menu option. Also, add a subfolder named Home under the Views folder.

    Then right-click the Models folder and select Add ➤ Class from the shortcut menu. This will open a dialog as shown in Figure 1-11.

    ../images/481875_1_En_1_Chapter/481875_1_En_1_Fig11_HTML.jpg

    Figure 1-11

    Adding a new class to the Models folder

    Name the class as AppMessage and click the Add button. Once the class gets added, write the code shown in Listing 1-1 into it.

    public class AppMessage

    {

        public string Message { get; set; }

    }

    Listing 1-1

    AppMessage class

    The AppMessage class has just one public property called Message that represents a message to be displayed in the browser.

    Next, right-click the Controllers folder and select Add ➤ New Item from the shortcut menu. This will open the Add New Item dialog as shown in Figure 1-12.

    ../images/481875_1_En_1_Chapter/481875_1_En_1_Fig12_HTML.jpg

    Figure 1-12

    Adding a new controller to the project

    Select Controller Class from the list, name the controller HomeController, and click the Add button. Once the HomeController gets added, remove the default Index() action from it, and add two new actions as shown in Listing 1-2.

    public IActionResult Index()

    {

        AppMessage obj = new AppMessage() {

            Message = Hello World!

        };

        return View(obj);

    }

    [HttpPost]

    public IActionResult Index(AppMessage obj)

    {

        ViewBag.Message = Message changed.;

        return View(obj);

    }

    Listing 1-2

    HomeController contains two actions

    The first Index() action gets called when the first request to the application is made. Inside, you create a new object of AppMessage and set its Message property to Hello World!. This object is passed to the view using the View() method . The View() method exists in the base class of HomeController – Controller.

    Note

    You will observe that the HomeController class inherits from the Controller class. The Controller base class resides in the Microsoft.AspNetCore.Mvc namespace. While working with ASP.NET Core MVC projects, you will need to use this namespace in many places. You also need to use the HelloWorldMVC.Models namespace in order to be able to use the AppMessage class.

    The second Index() action is called when the HTML form is POSTed to the server. This HTML form is part of the view file, and you will create it later in this section. This Index() action receives the message entered by the user wrapped in the object of AppMessage. This mapping of textbox value to the Message property of AppMessage is accomplished by the framework through a process called model binding. Inside, you pass the object to the View() method as before. Additionally, you also set the Message property on the ViewBag object . ViewBag is a built-in object provided by ASP.NET Core and is used to pass data from the controller to the view. This Message value will be outputted on the view.

    Note that the second Index() action is decorated with the [HttpPost] attribute. The [HttpPost] attribute indicates that the underlying action will be invoked only for POST requests.

    Note

    In the preceding code, you created two overloads of the Index() action. However, keep in mind that this overloading works as expected because they are dealing with different types of requests. For example, the first Index() handles the initial request to the action, whereas the second Index() handles form submission POST request. If you comment out the [HttpPost] attribute added to the second Index(), you will get AmbiguousMatchException indicating that the framework can’t decide which action to use. You can use the [ActionName] attribute to overcome this problem. You will use [ActionName] in later chapters of this book.

    So far, you have completed the model and the controller required by the application. Let’s add the final piece – view – that houses the user interface of the application.

    To add a view, right-click the Views ➤ Home folder and select the Add New Item menu option. This time, select Razor View and specify the name to be Index.cshtml (Figure 1-13).

    ../images/481875_1_En_1_Chapter/481875_1_En_1_Fig13_HTML.jpg

    Figure 1-13

    Adding Index view to the project

    Note that the name of the action matches with the name of the view. This way, the View() method assumes that the model is to be supplied to the Index view.

    The Index view will use what are known as Tag Helpers to render the user interface. By default, Tag Helpers are not available to a view. To add support for Tag Helpers, open the Add New Item dialog again and select Razor View Imports (Figure 1-14).

    ../images/481875_1_En_1_Chapter/481875_1_En_1_Fig14_HTML.jpg

    Figure 1-14

    Adding a view imports file

    Once the view imports file (_ViewImports.cshtml) is added, write this line of code into it:

    @addTagHelper *,Microsoft.AspNetCore.Mvc.TagHelpers

    Using the @addTagHelper directive adds Tag Helpers to the project from the assembly that follows. In this case, built-in Tag Helpers reside in the Microsoft.AspNetCore.Mvc.TagHelpers assembly. The ∗ indicates that all Tag Helpers from the specified assembly are to be added.

    Note

    In subsequent chapters, you will learn about Tag Helpers in more detail. For now, keep in mind that they allow you to render the user interface elements of an ASP.NET Core web application.

    Next, open the Index.cshtml file and write the markup and code shown in Listing 1-3 into it.

    @model HelloWorldMVC.Models.AppMessage

        

            Hello World App

        

        

            

    @Model.Message

            


            

    @ViewBag.Message

            

    Home asp-action=Index method=post>

                

                

                text asp-for=Message />

                

                

            

        

    Listing 1-3

    Markup and code from Index view

    The view markup begins with the @model directive that specifies the type of model class being supplied to this view. Recollect that you are supplying an object of AppMessage class to the View() method. Therefore, @model specifies AppMessage as the view’s model type.

    The actual model object passed through the View() method can be accessed inside a view file using the Model property. In this example, you output the model’s Message property on the response using @ razor expression syntax. Similarly, the code also renders ViewBag’s Message property on the response.

    The Form Tag Helper (

    tag) renders an HTML form with three fields – a label, a textbox, and a button. Notice that the Form Tag Helper looks quite similar to the standard HTML tag. However, it has some special attributes such as asp-controller and asp-action. The asp-controller and asp-action attributes decide which controller and action will be used to process the form upon submission. In this case, the form will be submitted to the Index() action of HomeController. The method attribute configures the form to use the POST method to submit its content.

    The Label and Input Tag Helpers use the asp-for attribute to bind the underlying form field to the model’s Message property. This way, the textbox displays the value of the Message property. A user can edit the textbox value and hit the Submit button.

    This completes the Index view. Before you run the application, you need to configure the application’s startup. To do so, open the Startup.cs file and go to its ConfigureServices() method . Modify ConfigureServices() as shown in Listing 1-4.

    public void ConfigureServices(IServiceCollection services)

    {

        services.AddControllersWithViews();

    }

    Listing 1-4

    ConfigureServices() method

    The code shown in Listing 1-4 calls the services.AddControllersWithViews() extension method of IServiceCollection. Doing so registers several built-in types related to MVC applications with ASP.NET Core’s dependency injection framework.

    Now modify the Configure() method inside Startup.cs as shown in Listing 1-5.

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

    {

        if (env.IsDevelopment())

        {

            app.UseDeveloperExceptionPage();

        }

        app.UseRouting();

        app.UseEndpoints(endpoints =>

        {

          endpoints.MapControllerRoute(

           name: default,

           pattern: {controller=Home}/{action=Index}/{id?});

        });

    }

    Listing 1-5

    Configure() method

    The Configure() method is used to configure your application’s HTTP pipeline. It adds the required middleware to the HTTP pipeline. In this example, the code checks whether the application is running in development environment or production environment. This is done using the IsDevelopment() method of IWebHostEnvironment. Accordingly, UseDeveloperExceptionPage() is called to add developer exception page middleware to the pipeline. This middleware is responsible for displaying the actual exception details in the browser whenever an error occurs.

    Finally, the code adds routing capabilities to the application. The UseRouting() call adds what is known as the endpoint routing middleware to the HTTP pipeline. The UseEndpoints() call wires the endpoint middleware in the application. The pattern mentioned inside the UseEndpoints() handles the request URLs of the form https://localhost:1234//. For example, the Index() can be invoked using this URL: https://localhost:1234/Home/Index. The UseEndpoints() method also configures the HomeController to be the default controller and Index() action to be the default action for the routes.

    This completes the application. At this time, your Solution Explorer should resemble Figure 1-15.

    ../images/481875_1_En_1_Chapter/481875_1_En_1_Fig15_HTML.jpg

    Figure 1-15

    View of Solution Explorer with various files

    Confirm whether you have added various files to the correct folders as shown in Solution Explorer and run the application by pressing F5.

    Note

    While working with ASP.NET Core MVC projects, you can store models and controllers in any folder though many developers store them in Models and Controllers folders, respectively (like you did in the preceding example). For example, you can store models inside a folder named AppModels. The recommended location for view files is the Views folder (or its subfolders) because by default the framework searches for views in that folder.

    If all goes well, Visual Studio will start IIS Express and you will see the application’s Index view loaded in the browser. By default, the application will show the Hello World! message. Enter some different message in the textbox and click the Submit button. The heading should now reflect the newly entered message.

    Creating an ASP.NET Core Razor Pages Project

    In this section, you will create the same Hello World application using ASP.NET Core Razor Pages. To begin developing this application, create a new ASP.NET Core project using the Empty project template. This task is exactly the same as before with an exception that the project name this time is HelloWorldRazorPages.

    Once the new project gets created, add two folders to it, namely, Models and Pages. The purpose of the Models folder is to store model classes, whereas the Pages folder is used to store Razor Pages and associated page models.

    Then add the AppMessage class to the Models folder as in the preceding example. Also place the view imports file (_ViewImports.cshtml) to the Pages folder. Now right-click the Pages folder and select Add New Item from the shortcut menu. This time, add a new Razor Page named Index.cshtml to the Pages folder (Figure 1-16).

    ../images/481875_1_En_1_Chapter/481875_1_En_1_Fig16_HTML.jpg

    Figure 1-16

    Adding a new Razor Page

    When you add an Index Razor Page, actually two files get added – Index.cshtml and Index.cshtm.cs. The Index.cshtml file houses the Razor code and markup that makes the user interface, whereas the Index.cshtml.cs file represents the page model class.

    To get started, your Solution Explorer should resemble Figure 1-17.

    ../images/481875_1_En_1_Chapter/481875_1_En_1_Fig17_HTML.jpg

    Figure 1-17

    HelloWorldRazorPages project in Solution Explorer

    Now open the Index.cshtml.cs file. This file contains a page model class named IndexModel. Modify the IndexModel class as shown in Listing 1-6.

    public class IndexModel : PageModel

    {

        [BindProperty]

        public AppMessage Heading { get; set; }

        public string SubHeading { get; set; }

        public void OnGet()

        {

            this.Heading = new AppMessage();

            this.Heading.Message = Hello World!;

        }

        public void OnPost()

        {

            this.SubHeading = Message changed.;

        }

    }

    Listing 1-6

    Index page model class

    The IndexModel class inherits from the PageModel class residing in the Microsoft.AspNetCore.Mvc.RazorPages namespace. The IndexModel class consists of two public properties and two public methods.

    The Heading public property is of type AppMessage and is decorated with the [BindProperty] attribute. The [BindProperty] attribute indicates that this property will participate in the model binding.

    The SubHeading string property is used to display a message to a user whenever textbox value is changed.

    The OnGet() method is called a page handler and handles GET requests to the page. Similar to OnGet(), you can have OnPost(), OnPut(), and OnDelete() page handlers to deal with POST, PUT, and DELETE verbs.

    The OnGet() page handler initializes the Heading property to a new AppMessage instance and also sets its Message property to Hello World!. The OnPost() page handler is invoked when a user hits the Submit button and POSTs the form to the server. Inside, the code sets the SubHeading property to a message. The Heading and SubHeading values are displayed on the Index.cshtml file. The markup and code of Index.cshtml is shown in Listing 1-7.

    @page

    @model HelloWorldRazorPages.Pages.IndexModel

        

            Hello World App

        

        

            

    @Model.Heading.Message

            


            

    @Model.SubHeading

            

    post>

                

                

                text asp-for=Heading.Message />

                

                

            

        

    Listing 1-7

    Displaying Heading and SubHeading

    Notice that Index.cshtml begins with the @page directive. The @page directive marks the .cshtml file as a Razor Page. The @model directive points to the type of page model class (IndexModel in this case).

    The heading of the page displays AppMessage’s Message property. Notice how the Heading object from the page model class is accessed using the Model property. This way, all the public properties of the page model class can be accessed using the Model object. The SubHeading is also rendered in a similar way.

    The form tag has a method attribute set to post indicating that the form will use the POST method during submission. Inside, the form houses a label, a textbox, and a button as in the preceding example.

    This completes the Index Razor Page. Before you run the application, you need to configure the startup using the Startup.cs file. So open the Startup.cs file and modify the ConfigureServices() and Configure() methods as shown in Listing 1-8.

    public void ConfigureServices(IServiceCollection services)

    {

        services.AddRazorPages();

    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

    {

        if (env.IsDevelopment())

        {

            app.UseDeveloperExceptionPage();

        }

        app.UseRouting();

        app.UseEndpoints(endpoints =>

        {

          endpoints.MapRazorPages();

        });

    }

    Listing 1-8

    Configuring application startup

    The code from Listing 1-9 should look familiar to you. This time, we used AddRazorPages() to register Razor Pages–related services with the dependency injection framework. Razor Pages uses a slightly different routing mechanism than MVC applications. The routing and URL handling is defined in the individual page using the @page directive. By default, Razor Pages URLs follow this pattern: https://localhost:1234/. For example, to access the Index page, the URL will be https://localhost:1234/Index. This configuration is done using the MapRazorPages() method inside the UseEndpoints() call.

    Now run the application by pressing F5 and test the functionality by specifying a new message.

    Note

    When you run the MVC and Razor Pages applications, the browser’s address bar may show only this URL – https://localhost:1234 (port number will be different for you). That’s because /Home/Index is the default for MVC applications and /Index is the default for Razor Pages applications. You can manually enter the full URL to confirm that they are indeed handled by the appropriate action and page handler, respectively.

    Creating an ASP.NET Core Web API Project

    Now that you have some idea about ASP.NET Core MVC and Razor Pages applications, let’s create a Web API that returns messages when called.

    To begin creating a Web API, create a new project named HelloWorldWebApi based on the Empty project template. Web API uses a controller-centric approach to build RESTful services.

    Once a project is created, add the Models and Controllers folders to it. Also, add the AppMessage class to the Models folder. Since Web API is about

    Enjoying the preview?
    Page 1 of 1