Real-World Web Development with .NET 9 - Mark J. Price - E-Book

Real-World Web Development with .NET 9 E-Book

Mark J. Price

0,0
29,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.
Mehr erfahren.
Beschreibung

Real-World Web Development with .NET 9 equips you to build professional websites and services using proven technologies like ASP.NET Core MVC, Web API, and OData—trusted by organizations for delivering robust web applications.
You’ll learn to design and build efficient web applications with ASP.NET Core MVC, creating well-structured, maintainable code that follows industry best practices. From there, you’ll focus on Web API, building RESTful services that are both secure and scalable. Along the way, you’ll also explore testing, authentication, and containerization for deployment, ensuring that your solutions are fully production ready.
In the final part of the book, you will be introduced to Umbraco CMS, a popular content management system for .NET. By mastering this tool, you’ll learn how to empower users to manage website content independently.
By the end of this book, you'll not only have a solid grasp of controller-based development but also the practical know-how to build dynamic, content-driven websites using a popular .NET CMS.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 741

Veröffentlichungsjahr: 2024

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Real-World Web Development with .NET 9

First Edition

Build websites and services using mature and proven ASP.NET Core MVC, Web API, and Umbraco CMS

Mark J. Price

Real-World Web Development with .NET 9

First Edition

Copyright © 2024 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Senior Publishing Product Manager: Suman Sen

Acquisition Editor – Peer Reviews: Swaroop Singh

Project Editor: Janice Gonsalves

Content Development Editor: Matthew Davies

Copy Editor: Safis Editing

Technical Editor: Simanta Rajbangshi

Proofreader: Safis Editing

Indexer: Pratik Shirodkar

Presentation Designer: Rajesh Shirsath

Developer Relations Marketing Executive: Priyadarshini Sharma

First published: December 2024

Production reference: 1181224

Published by Packt Publishing Ltd.

Grosvenor House

11 St Paul’s Square

Birmingham

B3 1RB, UK.

ISBN 978-1-83588-038-8

www.packt.com

Contributors

About the author

Mark J. Price is a Microsoft Specialist: Programming in C# and Architecting Microsoft Azure Solutions, with over 20 years of experience. Since 1993, he has passed more than 80 Microsoft programming exams and specializes in preparing others to pass them. Between 2001 and 2003, Mark was employed to write official courseware for Microsoft in Redmond, USA. His team wrote the first training courses for C# while it was still an early alpha version. While with Microsoft, he taught “train-the-trainer” classes to get Microsoft Certified Trainers up to speed on C# and .NET. Mark has spent most of his career training a wide variety of students, from 16-year-old apprentices to 70-year-old retirees, with the majority being professional developers. Mark holds a BSc. degree in Hons Computer Science.

Thank you to all my readers. Your support means I get to write these books and celebrate your successes.

Special thanks to the readers who give me actionable feedback via my GitHub repository and email and interact with me and the book communities on Discord. You help make my books even better with every edition.

Extra special thanks to Troy, a reader who became a colleague, and more importantly, a good friend.

About the reviewer

Vishnu VG is a .NET programmer and software architect with over 17 years of experience in the IT industry. Based in Thiruvananthapuram, Kerala, India, his expertise lies in C# .NET, .NET Core, cloud platforms like AWS and Azure (holding an AWS Associate Certificate), Linux, serverless architectures, and container technologies. He is proficient in managing both on-premises and hybrid enterprise systems.

Beyond his technical skillset, Vishnu is a professional who actively engages with the developer community. Since 2021, he has held the title of AWS Community Builder. He is also passionate about knowledge sharing through his YouTube channel and podcast, both called Coding Talks with Vishnu VG.

Learn more on Discord

To join the Discord community for this book – where you can share feedback, ask questions to the author, and learn about new releases – follow the QR code below:

https://packt.link/RWD9

Contents

Preface

Where to find the code solutions

What this book covers

What you need for this book

Downloading the color images of this book

Conventions

Get in touch

Leave a Review!

Download the free PDF and supplementary content

Introducing Web Development Using Controllers

Understanding ASP.NET Core

A brief history of ASP.NET Core

Classic ASP.NET versus modern ASP.NET Core

Building websites using ASP.NET Core

Comparison of file types used in ASP.NET Core

Building websites using a content management system

Building web applications using SPA frameworks

Building web and other services

Cloud providers and deployment tools

Structuring projects and managing packages

Structuring projects in a solution

Structuring folders in a project

Folder structure based on technological concerns

Folder structure based on features

Folder structure summary

Central Package Management

Making good use of the GitHub repository for this book

Understanding the solution code on GitHub

Downloading solution code from the GitHub repository

Using Git with VS Code and the command prompt

Cloning the book solution code repository

Building an entity model for use in the rest of the book

Northwind database SQL scripts

Installing Docker and the Azure SQL Edge container image

Running the Azure SQL Edge container image

Running a container using the user interface

Connecting to Azure SQL Edge in a Docker container

Connecting from Visual Studio

Connecting from VS Code

Creating the Northwind database using a SQL script

Removing Docker resources

Setting up the EF Core CLI tool

Creating a class library for entity models

Creating a class library for a database context

Setting the user and password for SQL Server authentication

Registering dependency services

Improving the class-to-table mapping

Testing the class libraries using xUnit

Practicing and exploring

Exercise 1.1 – Online material

Exercise 1.2 – Practice exercises

Troubleshooting web development

Exercise 1.3 – Test your knowledge

Know your webbreviations

Exercise 1.4 – Explore topics

Summary

Building Websites Using ASP.NET Core MVC

Setting up an ASP.NET Core MVC website

Creating an ASP.NET Core MVC website

Creating the authentication database for SQL Server LocalDB

Changing the port numbers and starting the website

Understanding browser requests during development

Exploring visitor registration

Reviewing an MVC website project structure

Reviewing the ASP.NET Core Identity database

Configuring files included in an ASP.NET Core project

Project file build actions

Exploring an ASP.NET Core MVC website

ASP.NET Core MVC initialization

What does UseMigrationsEndPoint do?

Controlling the hosting environment

The default MVC route

Controllers and actions

The responsibilities of a controller

Routing to controllers

The ControllerBase class

The Controller class

Reviewing the project template controller

The view search path convention

Logging using the dependency service

Using entity and view models

View model example

Implementing views

How cache busting with Tag Helpers works

Prototyping with Bootstrap

Breakpoints and containers

Rows and columns

Color themes

Tables

Buttons and links

Badges

Alerts

Good practice for Bootstrap

Customizing an ASP.NET Core MVC website

Defining a custom style

Setting up the category images

Razor syntax and expressions

Defining a typed view

Testing the home page with categories

Cross-functional filters

Using a filter to define a custom route

Temporarily storing data

Practicing and exploring

Exercise 2.1 – Online material

Exercise 2.2 – Practice exercises

Practice building UIs with Bootstrap

Exercise 2.3 – Test your knowledge

Exercise 2.4 – Explore topics

Summary

Model Binding, Validation, and Data Using EF Core

Model binding and validation

How model binding works

How validation rules are defined

Passing parameters using a route value

Disambiguating action methods

Model binders in detail

Passing a route parameter

Passing a form parameter

Avoiding over-posting aka mass assignment attacks

Returning HTTP error status codes

BadRequest

NotFound

Unauthorized

Forbid

Conflict

UnprocessableEntity

StatusCode

Problem

ValidationProblem

Modifying data using EF Core and ASP.NET Core

Displaying Northwind suppliers

Inserting, updating, and deleting suppliers

Manually trying to insert, update, and delete

Protecting against CSRF attacks

How CSRF attacks work

How anti-forgery tokens prevent CSRF

How to use Html.AntiForgeryToken()

Querying a database and using display templates

Improving scalability using asynchronous tasks

Threads and tasks on a web server

Making controller action methods asynchronous

Practicing and exploring

Exercise 3.1 – Online material

Exercise 3.2 – Practice exercises

Practice implementing MVC by implementing a category detail page

Exercise 3.3 – Test your knowledge

Exercise 3.4 – Explore topics

Summary

Building and Localizing Web User Interfaces

Defining web user interfaces with Razor Views

Using shared layouts with Razor Views

Defining views with HTML Helper methods

Defining web user interfaces with Tag Helpers

Comparing HTML Helpers and Tag Helpers

Exploring the Anchor Tag Helper

Exploring the Cache Tag Helpers

Exploring the Environment Tag Helper

Exploring Forms-related Tag Helpers

Localizing web user interfaces with ASP.NET Core

Working with cultures

Localizing your user interface

Web user interface localization

Creating resource files

If you are using Visual Studio

If you are using VS Code

Other resource file tools

Managing resource files

Localizing Razor Views with an injected view localizer

Understanding the Accept-Language header

Practicing and exploring

Exercise 4.1 – Online material

Exercise 4.2 – Practice exercises

Practice creating a custom Tag Helper

Practice unit testing MVC controllers

Exercise 4.3 – Test your knowledge

Exercise 4.4 – Explore topics

Summary

Authentication and Authorization

Introducing authentication and authorization

Key concepts of authentication and authorization

Identity management

Authentication schemes

Role-based and claims-based authorization

Security best practices

Cookie-based authentication

Password verifier best practices

Implementing authentication and authorization

Defining policies

External authentication

Securing APIs with JWT

Securing controller action methods using filters

Enabling role management and creating a role programmatically

Cross-functional filters

Authorization filter (IAuthorizationFilter)

Resource filter (IResourceFilter)

Action filter (IActionFilter)

Exception filter (IExceptionFilter)

Result filter (IResultFilter):

Common benefits of all filters

Practicing and exploring

Exercise 5.1 – Online material

Exercise 5.2 – Practice exercises

Auth0 integration

Exercise 5.3 – Test your knowledge

Exercise 5.4 – Explore topics

Summary

Performance Optimization Using Caching

Introducing caching with ASP.NET Core

General caching guidelines

Reviewing types of caching

Caching HTTP responses for websites

Common cache-control directives

Controlling cache-control directives in ASP.NET Core

Exploring cache-control directives

Seeing the effect of cache-control directives

Summary of caching types

Output caching

Output caching endpoints

Output caching MVC views

Varying output cached data by query string

Disabling output caching to avoid confusion

Object caching

Caching objects using in-memory caching

Expirations for in-memory caching

Exploring in-memory object caching

Caching objects using distributed caching

Hybrid object caching

Creating data repositories with caching for entities

Configuring the customer repository

More techniques to improve scalability

Horizontal scaling with load balancing

Asynchronous programming

Database optimizations

Message queues and background services

Auto-scaling in the cloud

CDN

Health checks and monitoring

Practicing and exploring

Exercise 6.1 – Online material

Exercise 6.2 – Practice exercises

Practicing improving scalability by understanding and implementing async action methods

Exercise 6.3 – Test your knowledge

Exercise 6.4 – Explore topics

Summary

Web User Interface Testing Using Playwright

Introducing web user interface testing

Types of web UI testing

What should you test in a web UI?

Challenges and good practices with web UI testing

The roles of developers and testers

Developers and web UI testing

Testers and web UI testing

Collaboration between developers and testers

Real-life applications of web user interface testing

E-commerce websites: preventing cart and checkout failures

Financial applications: ensuring data integrity and accuracy

Healthcare portals: guaranteeing user and data safety

Banking applications: avoiding security and transaction errors

Government and public sector: ensuring accessibility compliance

SaaS platforms: preventing downtime and data loss

Travel and booking platforms: ensuring smooth transactions

Testing web user interfaces using Playwright

What can Playwright do?

Benefits for .NET developers

Alternatives to Playwright

Common Playwright testing types

Common Playwright testing methods

Common Playwright locator methods

Common Playwright locator automation methods

Testing common scenarios

Page navigation and title verification

Interacting with a web user interface

Filling input boxes and clicking elements

Form submission, authentication, and validation

Responsive design testing

Emulating screen sizes

Emulating devices

Emulating locale, time zone, and geolocation

Emulating dark mode and color schemes

Customizing the user agent, disabling JavaScript, and going offline

Single-Page Applications (SPAs) and dynamic content

Generating tests with the Playwright Inspector

Practicing and exploring

Exercise 7.1 – Online-only material

Exercise 7.2 – Practice exercises

Exercise 7.3 – Test your knowledge

Exercise 7.4 – Explore topics

Summary

Configuring and Containerizing ASP.NET Core Projects

Configuring dependency services

Introducing dependency injection

Why use DI?

Injection mechanisms of DI in .NET

Examples in modern .NET

Constructor injection example

Property injection example

Method injection example

Dependency graphs and service resolution

Registering dependency service lifetimes

When are exceptions thrown?

Registering services for features using extension methods

When you cannot use constructor injection

Using scoped services in middleware

Resolving services at startup

DI and MVC controller action methods

DI and MVC views

Disposing services

Best practices for DI

Configuring the HTTP pipeline

Understanding endpoint routing

Benefits of endpoint routing

Configuring endpoint routing

Reviewing the default endpoint routing configuration

Setting up the HTTP pipeline

Summarizing key middleware extension methods

Visualizing the HTTP pipeline

Implementing an anonymous inline delegate as middleware

Configuring options

Configuration sources

Configuration classes and interfaces

How to manually set up configuration

Understanding IConfiguration and IConfigurationRoot

IConfiguration for combined settings from all providers

IConfigurationRoot for more advanced scenarios

Showing providers and settings

Configuration overriding in production deployments

Configuration overriding in Docker

Configuration overriding in Kubernetes

Loading configuration using the Options pattern

Using IOptionsSnapshot and IOptionsMonitor

Configuration validation

Using custom configuration providers

Containerizing ASP.NET Core projects

How containers work and their benefits

Docker and .NET Aspire

Installing Docker and using prebuilt images

Aspire project types

Aspire resource types

Developer dashboard for monitoring

Adding Aspire to an existing solution

Deployment with Aspire

Practicing and exploring

Exercise 8.1 – Online material

Exercise 8.2 – Practice exercises

Exercise 8.3 – Test your knowledge

Exercise 8.4 – Explore topics

Summary

Building Web Services Using ASP.NET Core Web API

Introducing web services

Aspects of RESTful services

Statelessness

Resource-based

Uniform interface

Client-server architecture

Cacheability

Layering

Representation of resources

Idempotency

Hypermedia as the Engine of Application State (HATEOAS)

Why REST matters

Understanding HTTP versions

HTTP/0.9 (1991)

HTTP/1.0 (1996)

HTTP/1.1 (1997, updated in 1999)

HTTP/2 (2015)

HTTP/3 (2020)

Understanding HTTP requests and responses for web APIs

GET requests

Common response status codes

Caching requests example

POST, PUT, and other requests

Creating an ASP.NET Core Web API with controllers project

Trying out the weather forecast web service’s functionality

Creating a web service for the Northwind database

Controlling XML serialization

Routing web service requests to action methods

Route constraints

Short-circuit routes

Understanding action method return types

Configuring the customer repository and Web API controller

Specifying problem details

Documenting and trying out web services

Making GET requests using a browser

Making GET requests using HTTP/REST tools

Making other requests using HTTP/REST tools

Passing environment variables

Understanding the OpenAPI Specification

Generating clients using an OpenAPI specification

Caching and logging

Caching HTTP responses for web services

Enabling HTTP logging

Support for logging additional request headers in W3CLogger

Logging and security principles

Avoid logging sensitive information

Mask or obfuscate sensitive data

Avoid logging request and response bodies for sensitive endpoints

Use structured logging for sensitive data management

Log security events without sensitive data

Beware of third-party library logging

Log errors with caution

Consuming web services using HTTP clients

Understanding HttpClient

Configuring HTTP clients using HttpClientFactory

Getting customers as JSON in the controller

Starting multiple projects

If you are using Visual Studio

If you are using VS Code

Starting the web service and MVC client projects

Relaxing the same origin security policy using CORS

Configuring HTTP logging for the web service

Creating a .NET client

Understanding CORS

Understanding other CORS policy options

Understanding identity services

JWT bearer authorization

Authenticating service clients using JWT bearer authentication

Practicing and exploring

Exercise 9.1 – Online material

Improved route tooling

Implementing advanced features for web services

Exercise 9.2 – Practice exercise

Creating and deleting customers with HttpClient

Exercise 9.3 – Test your knowledge

Exercise 9.4 – Explore topics

Summary

Building Web Services Using ASP.NET Core OData

Understanding OData

Understanding the OData standard

Benefits of OData

Standardized querying

Cross-platform interoperability and integration with Microsoft ecosystem

Self-describing and rich metadata

Supports RESTful principles and CRUD operations

Supports multiple data formats

Built-in support for data relationships

Extensibility

Standard security features

Disadvantages of OData

Building a web service that supports OData

Defining OData models for the EF Core models

Testing the OData models

Creating and testing OData controllers

Exploring OData services using HTTP/REST tools

Creating an HTTP file for making requests

Understanding OData queries

OData standard query options

OData operators

OData functions

Exploring OData queries

Using logs to review the efficiency of OData requests

Implementing versions and data modifications

Versioning OData controllers

Enabling entity inserts, updates, and deletes

Building clients for OData services

Calling services in the Northwind MVC website

Revisiting the introductory query

Practicing and exploring

Exercise 10.1 – Online material

Exercise 10.2 – Practice exercises

Exercise 10.3 – Test your knowledge

Exercise 10.4 – Explore topics

Summary

Building Web Services Using FastEndpoints

Introducing FastEndpoints

Pros and cons of FastEndpoints

What makes it “fast”?

How to define an endpoint

Example FastEndpoints endpoint implementation

Implementing FastEndpoints

Adding FastEndpoints to an empty ASP.NET Core project

Enabling FastEndpoints and defining endpoints

Configuring FastEndpoints

Configuration methods and properties

Mapping requests and responses to entity models

Practicing and exploring

Exercise 11.1 – Online material

Exercise 11.2 – Practice exercises

Exercise 11.3 – Test your knowledge

Exercise 11.4 – Explore topics

Summary

Web Service Integration Testing

Basics of integration testing

Testing terminology

Attributes of all good tests

Test outcomes

Why false positives and false negatives are bad

Test doubles, mocks, and stubs

Which external systems to test

Sharing fixtures in integration tests

Understanding web service functional and end-to-end testing

End-to-end test scenario

Functional test scenario

Test automation

Integration testing with data stores

Developer instances of the database and migrations

Data lifecycle

Testing web services using xUnit

Unit testing using xUnit

Common xUnit attributes

Web service hosting with WebApplicationFactory

Enabling an ASP.NET Core project to be tested

Creating the test project

Mocking in tests

Libraries for mocking

Using NSubstitute to create test doubles

Mocking with NSubstitute example

Testing services using dev tunnels

Installing the dev tunnel CLI

Exploring a dev tunnel with the CLI and an echo service

Exploring a dev tunnel with an ASP.NET Core project

Practicing and exploring

Exercise 12.1 – Online-only material

Exercise 12.2 – Practice exercises

Create integration tests for three web service technologies

Exercise 12.3 – Test your knowledge

Exercise 12.4 – Explore topics

Summary

Web Content Management Using Umbraco

Understanding the benefits of a CMS

Understanding basic CMS features

Understanding enterprise CMS features

Understanding CMS platforms

Introducing Umbraco CMS

Why is Umbraco popular?

Umbraco versions and setup

Installing Umbraco CMS

Creating and initializing a new Umbraco project

Unattended installs

Defining document types

Example document types

Creating a document type

Setting up languages

Defining a document template

Reviewing the website

Adding a home page as content

Creating and publishing a French variant home page

Working with media

Good media practices

Organizing media using folders

Using tags to enhance searchability

Optimizing image sizes before uploading

Using meaningful file names and alt text

Leveraging image cropping and variants

Avoiding duplicate media uploads

Removing unused media regularly

Using Umbraco’s built-in permissions for media access

Training editors on best practices and providing resources

Uploading images to Umbraco CMS

Practicing and exploring

Exercise 13.1 – Online material

Exercise 13.2 – Practice exercises

Exercise 13.3 – Test your knowledge

Exercise 13.4 – Explore topics

Summary

Customizing and Extending Umbraco

Techniques for customizing and extending Umbraco

Building custom property editors for enhanced content creation

Integrating third-party APIs to enhance functionality

Custom workflow automation for content approval

Multilingual capabilities with custom language switching

Customizing Umbraco behavior using settings

Content settings

Security settings

Imaging settings

Global settings

Content version cleanup

Working with views and Razor syntax

What is IPublishedContent?

Core functionality of IPublishedContent

Using IPublishedContent with ModelsBuilder

Rendering fields in a strongly typed view

Rendering complex field types

Rendering Rich Text Editor (RTE) fields

Rendering Multi-Node Tree Picker (MNTP) fields

Handling Media Picker fields

Handling Nested Content and Block List editors

Common considerations

Accessing member data

Using Models Builder

The UmbracoHelper class

Retrieving content by ID

Retrieving media by ID

Rendering a content template

Getting dictionary values

Querying content using LINQ

Checking member authorization

UmbracoHelper summary

Practicing and exploring

Exercise 14.1 – Online material

Exercise 14.2 – Practice exercises

The Starter Kit

Extending Umbraco

Exercise 14.3 – Test your knowledge

Exercise 14.4 – Explore topics

Summary

Epilogue

Next steps on your web development learning journey

Companion books to continue your learning journey

Other books to take your learning further

The next edition for .NET 10

Good luck!

Index

Download the free PDF and supplementary content

Landmarks

Cover

Index

Leave a Review!

Thank you for purchasing this book from Packt Publishing—we hope you enjoy it! Your feedback is invaluable and helps us improve and grow. Once you’ve completed reading it, please take a moment to leave an Amazon review; it will only take a minute, but it makes a big difference for readers like you.

Scan the QR code below to receive a free ebook of your choice.

https://packt.link/NzOWQ

Download the free PDF and supplementary content

Thanks for purchasing this book!

Do you like to read on the go but are unable to carry your print books everywhere?

Is your eBook purchase not compatible with the device of your choice?

Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.

Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.

Additionally, with this book you get access to supplementary/bonus content for you to learn more. You can use this to add on to your learning journey on top of what you have in the book.

The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily.

Follow these simple steps to get the benefits:

Scan the QR code or visit the link below:

https://packt.link/supplementary-content-9781835880388

Submit your proof of purchase.Submit your book code. You can find the code under the Summary section of Chapter 7.That’s it! We’ll send your free PDF, supplementary content, and other benefits to your email directly.