Web API Development with ASP.NET Core 8: Learn techniques, patterns, and tools for building high-performance, robust, and scalable web APIs / Разработка веб-API с использованием ASP.NET Core 8: Изучите методы, шаблоны и инструменты для создания высокопроизводительных, надежных и масштабируемых веб-API Год издания: 2024 Автор: Xiaodi Yan / Сяоди Ян Издательство: Packt Publishing ISBN: 978-1-80461-095-4 Язык: Английский Формат: PDF, EPUB Качество: Издательский макет или текст (eBook) Интерактивное оглавление: Да Количество страниц: 804 Описание: Develop web API applications using design patterns, advanced customization, and cutting-edge technologies, such as SignalR, gRPC, and GraphQL, while leveraging powerful cloud platforms and tools to accelerate development Key Features Gain proficiency in building modern ASP.NET Core web API applications Develop the skills to effectively test, debug, and secure your web API applications Streamline development workflows and boost productivity with cloud computing platforms and industry-standard CI/CD tools Purchase of the print or Kindle book includes a free PDF eBook Book Description Web API applications have become increasingly significant in recent years, fueled by the ever-accelerating pace of technological advancements. However, with this rapid evolution comes a pressing challenge: the need to create web API applications that are not only functional but also adaptable, maintainable, and scalable to meet the demands of users and businesses alike. This book will help you address this challenge head-on, equipping you with the knowledge and skills required to develop web API applications from scratch. By providing a deeper understanding of the various protocols implemented by ASP.NET Core, including RESTful, SignalR (WebSocket), gRPC, and GraphQL, supplemented by practical examples and optimization techniques, such as using middleware, testing, caching, and logging, this book offers invaluable insights for both newcomers as well as seasoned developers to meet modern web development requirements. Additionally, you’ll discover how to use cloud platforms such as Azure and Azure DevOps to enhance the development and operational aspects of your application. By the end of the book, you’ll be fully prepared to undertake enterprise-grade web API projects with confidence, harnessing the latest advancements in ASP.NET Core 8 to drive innovation. What you will learn Build a strong foundation in web API fundamentals Explore the ASP.NET Core 8 framework and other industry-standard libraries and tools for high-performance, scalable web APIs Apply essential software design patterns such as MVC, dependency injection, and the repository pattern Use Entity Framework Core for database operations and complex query creation Implement robust security measures to protect against malicious attacks and data breaches Deploy your application to the cloud using Azure and leverage Azure DevOps to implement CI/CD Who this book is for This book is for developers who want to learn how to build web APIs with ASP.NET Core and create flexible, maintainable, scalable applications with .NET platform. Basic knowledge of C#, .NET, and Git will assist with understanding the concepts more easily. Разрабатывайте приложения web API с использованием шаблонов проектирования, расширенной настройки и передовых технологий, таких как SignalR, gRPC и GraphQL, используя при этом мощные облачные платформы и инструменты для ускорения разработки Ключевые функции Получите навыки в создании современных ASP.NET Базовых приложений web API Развивайте навыки эффективного тестирования, отладки и обеспечения безопасности ваших приложений Web API Оптимизируйте рабочие процессы разработки и повышайте производительность благодаря платформам облачных вычислений и стандартным инструментам CI/CD При покупке книги print или Kindle Book предоставляется бесплатная электронная книга в формате PDF Описание книги В последние годы приложения Web API приобретают все большее значение, чему способствуют постоянно ускоряющиеся темпы технологического прогресса. Однако в связи с такой быстрой эволюцией возникает острая проблема: необходимо создавать приложения web API, которые были бы не только функциональными, но и адаптируемыми, обслуживаемыми и масштабируемыми в соответствии с требованиями как пользователей, так и предприятий. Эта книга поможет вам справиться с этой задачей, вооружив знаниями и навыками, необходимыми для разработки приложений web API с нуля. Обеспечивая более глубокое понимание различных протоколов, реализуемых ASP.NET Основные языки, включая RESTful, SignalR (WebSocket), gRPC и GraphQL, дополненные практическими примерами и методами оптимизации, такими как использование промежуточного программного обеспечения, тестирование, кэширование и ведение журнала, в этой книге содержатся бесценные сведения как для новичков, так и для опытных разработчиков. соответствовать современным требованиям веб-разработки. Кроме того, вы узнаете, как использовать облачные платформы, такие как Azure и Azure DevOps, для улучшения аспектов разработки и эксплуатации вашего приложения. К концу прочтения книги вы будете полностью готовы уверенно работать над проектами web API корпоративного уровня, используя последние достижения в области ASP.NET Ядро 8 для стимулирования инноваций. Чему вы научитесь Создайте прочную основу для изучения основ веб-API Исследуйте ASP.NET Платформа Core 8 и другие стандартные отраслевые библиотеки и инструменты для создания высокопроизводительных и масштабируемых веб-API Применяйте основные шаблоны проектирования программного обеспечения, такие как MVC, внедрение зависимостей и шаблон репозитория Используйте Entity Framework Core для работы с базами данных и создания сложных запросов Примените надежные меры безопасности для защиты от вредоносных атак и утечек данных Разверните свое приложение в облаке с помощью Azure и используйте Azure DevOps для внедрения CI/CD Для кого предназначена эта книга Эта книга предназначена для разработчиков, которые хотят научиться создавать веб-API с помощью ASP.NET Core и создавать гибкие, поддерживаемые и масштабируемые приложения на платформе .NET. Базовые знания C#, .NET и Git помогут легче разобраться в концепциях.
Примеры страниц (скриншоты)
Оглавление
Preface xv 1 Fundamentals of Web APIs 1 What is a web API? 1 What is a REST API? 2 The constraints of REST 3 A REST API example 4 Is my web API RESTful? 5 Designing a REST-based API 6 Identifying the resources 7 Defining the relationships between resources 7 Identifying operations 8 Designing the URL paths for resources 9 Mapping API operations to HTTP methods 12 Assigning response codes 14 Documenting the API 16 RPC and GraphQL APIs 20 What is an RPC-based API? 20 What is a GraphQL API? 25 Real-time APIs 28 The problem with API polling 29 What is a real-time API? 30 Which real-time communication technology is best for your application? 33 Summary 34 2 Getting Started with ASP.NET Core Web APIs 35 Technical requirements 35 Setting up the development environment 36 Configuring VS Code 37 Checking the .NET SDK 38 Creating a simple REST web API project 39 Building and running the project 41 Building the project 42 Running the project 43 Changing the port number 45 Hot Reload 46 Testing the API endpoint 46 Swagger UI 46 Debugging 53 Understanding the MVC pattern 57 The model and the controller 57 Creating a new model and controller 59 Creating a service 62 Implementing a GET operation 64 Implementing a CREATE operation 65 Implementing an UPDATE operation 67 Dependency injection 68 Understanding DI 69 DI in ASP.NET Core 70 DI tips 84 Introduction to minimal APIs 85 Creating a simple endpoint 86 Using DI in minimal APIs 87 What is the difference between minimal APIs and controller-based APIs? 89 Summary 89 3 ASP.NET Core Fundamentals (Part 1) 91 Technical requirements 91 Routing 92 What is attribute routing? 92 Mapping HTTP methods to action methods 94 Route constraints 95 Binding source attributes 97 Configuration 99 Using appsettings.json 100 Using the options pattern 102 Other configuration providers 110 Environments 114 Understanding the launchSettings.json file 116 Setting the environment 118 Understanding the priorities of configuration and environment variables 122 Checking the environment in the code 123 Summary 125 4 ASP.NET Core Fundamentals (Part 2) 127 Technical requirements 128 Logging 128 Using built-in logging providers 128 Logging levels 132 Logging parameters 134 Using third-party logging providers 136 Structured logging 138 What should/shouldn’t we log? 143 Middleware 144 What is middleware? 144 Built-in middleware 154 Creating a custom middleware component 159 Summary 162 5 Data Access in ASP.NET Core (Part 1: Entity Framework Core Fundamentals) 163 Technical requirements 164 Why use ORM? 164 Configuring the DbContext class 166 Creating models 166 Creating and configuring the DbContext class 168 Creating the database 170 Adding seed data 173 Implementing CRUD controllers 173 Creating the controller 174 How controllers work 177 Basic LINQ queries 178 Querying the data 179 Filtering the data 181 Sorting and paging 182 Creating an entity 184 Updating an entity 185 Deleting an entity 190 Configuring the mapping between models and database 192 Mapping conventions 192 Data annotations 193 Fluent API 195 Separating the mapping configurations 198 Summary 200 6 Data Access in ASP.NET Core (Part 2 – Entity Relationships) 201 Technical requirements 202 Understanding one-to-many relationships 202 One-to-many configuration 202 One-to-many CRUD operations 207 Understanding one-to-one relationships 219 One-to-one configuration 219 One-to-one CRUD operations 222 Understanding many-to-many relationships 223 Many-to-many configuration 223 Many-to-many CRUD operations 228 Understanding owned entities 233 Summary 235 7 Data Access in ASP.NET Core (Part 3: Tips) 237 Technical requirements 238 Understanding DbContext pooling 238 Understanding the difference between tracking versus no-tracking queries 241 Understanding the difference between IQueryable and IEnumerable 245 Client evaluation versus server evaluation 248 Using raw SQL queries 251 FromSql() and FromSqlRaw() 252 SqlQuery() and SqlQueryRaw() 254 ExecuteSql() and ExecuteSqlRaw() 255 Using bulk operations 256 ExecuteUpdate() 256 ExecuteDelete() 257 Understanding concurrency conflicts 258 Native database-generated concurrency token 261 Application-managed concurrency token 263 Handling concurrency conflicts 264 Reverse engineering 265 Other ORM frameworks 268 Summary 269 8 Security and Identity in ASP.NET Core 271 Technical requirements 272 Getting started with authentication and authorization 272 Creating a sample project with authentication and authorization 273 Understanding the JWT token structure 285 Consuming the API 286 Configuring the Swagger UI to support authorization 288 Delving deeper into authorization 290 Role-based authorization 290 Claim-based authorization 295 Understanding the authorization process 300 Policy-based authorization 306 Managing users and roles 312 New Identity API endpoints in ASP.NET Core 8 313 Understanding OAuth 2.0 and OpenID Connect 316 What is OAuth 2.0? 316 What is OpenID Connect? 320 Integrating with other identity providers 322 Other security topics 323 Always use Hypertext Transfer Protocol Secure (HTTPS) 323 Using a strong password policy 324 Implementing two-factor authentication (2FA) 326 Implementing rate-limiting 327 Using model validation 327 Using parameterized queries 330 Using data protection 330 Keeping secrets safe 330 Keeping the framework up to date 331 Checking the Open Web Application Security Project (OWASP) Top 10 331 Summary 331 9 Testing in ASP.NET Core (Part 1 – Unit Testing) 333 Technical requirements 333 Introduction to testing in ASP.NET Core 334 Writing unit tests 335 Preparing the sample application 335 Setting up the unit tests project 337 Writing unit tests without dependencies 339 Writing unit tests with dependencies 342 Using FluentAssertions to verify the test results 347 Testing the database access layer 351 How can we test the database access layer? 351 Creating a test fixture 353 Using the test fixture 355 Writing tests for methods that change the database 357 Parallelism of xUnit 362 Using the repository pattern 365 Testing the happy path and the sad path 370 Summary 372 10 Testing in ASP.NET Core (Part 2 – Integration Testing) 373 Technical requirements 373 Writing integration tests 373 Setting up the integration test project 374 Writing basic integration tests with WebApplicationFactory 375 Testing with a database context 377 Testing with mock services 383 Testing with authentication and authorization 385 Preparing the sample application 385 Creating a test fixture 386 Creating the test class 386 Testing the anonymous API endpoints 387 Testing the authorized API endpoints 388 Code coverage 398 Using data collectors 399 Generating a code coverage report 401 Summary 405 11 Getting Started with gRPC 407 Technical requirements 407 Recap of gRPC 408 Setting up a gRPC project 408 Creating a new gRPC project 408 Understanding the gRPC project structure 409 Creating protobuf messages 415 Defining a protobuf message 416 Understanding field numbers 418 Understanding the field types 419 Other .NET types 422 Creating a protobuf service 430 Defining a unary service 431 Creating a gRPC client 433 Defining a server streaming service 437 Defining a client streaming service 440 Defining a bidirectional streaming service 443 Consuming gRPC services in ASP.NET Core applications 447 Updating proto files 449 Summary 451 Further reading 452 12 Getting Started with GraphQL 453 Technical requirements 454 Recap of GraphQL 454 Setting up a GraphQL API using HotChocolate 455 Adding mutations 459 Using variables in queries 462 Defining a GraphQL schema 463 Scalar types 463 Object types 465 Retrieving related objects using resolvers 467 Field resolvers 469 Resolver for a list of objects 472 Using data loaders 477 Batch data loader 480 Group data loader 482 Dependency injection 484 Using the Service attribute 485 Understanding the lifetime of the injected services 486 Interface and union types 487 Interfaces 488 Union types 493 Filtering, sorting, and pagination 500 Filtering 500 Sorting 511 Pagination 515 Visualizing the GraphQL schema 524 Summary 526 Further reading 526 13 Getting Started with SignalR 527 Technical requirements 527 Recap of real-time web APIs 528 Setting up SignalR 528 Building SignalR clients 531 Building a TypeScript client 531 Building a Blazor client 539 Using authentication and authorization in SignalR 543 Adding authentication and authorization to the SignalR server 544 Adding a login endpoint 547 Authenticating the TypeScript client 548 Authenticating the Blazor client 551 Managing users and groups 553 Managing events in SignalR 553 Sending a message to a specific user 555 Using strongly typed hubs 557 Joining groups 559 Sending a message to a group 561 Sending messages from other services 563 Configuring SignalR hubs and clients 565 Configuring SignalR hubs 565 HTTP configuration options 567 Automatically reconnecting 568 Scaling SignalR 573 Summary 574 14 CI/CD for ASP.NET Core Using Azure Pipelines and GitHub Actions 575 Technical requirements 576 Introduction to CI/CD 576 CI/CD concepts and terminologies 578 Understanding the importance of CI/CD 579 Containerizing ASP.NET Core applications using Docker 580 What is containerization? 580 Installing Docker 581 Understanding Dockerfiles 583 Building a Docker image 587 Running a Docker container 589 CI/CD using Azure DevOps and Azure Pipelines 593 Preparing the source code 593 Creating Azure resources 594 Creating an Azure DevOps project 595 Creating a pull request pipeline 597 Publishing the Docker image to ACR 605 Deploying the application to Azure Web App for Containers 611 Configuring settings and secrets 615 GitHub Actions 615 Preparing the project 615 Creating GitHub Actions 616 Pushing a Docker image to ACR 620 Summary 622 15 ASP.NET Core Web API Common Practices 623 Technical requirements 623 Common practices of ASP.NET web API development 624 Using HTTPS instead of HTTP 624 Using HTTP status codes correctly 624 Using asynchronous programming 626 Using pagination for large collections 629 Specifying the response types 632 Adding comments to the endpoints 634 Using System.Text.Json instead of Newtonsoft.Json 637 Optimizing the performance by implementing caching 638 In-memory caching 639 Distributed caching 645 Response caching 651 Output caching 652 What caching strategy should I use? 655 Using HttpClientFactory to manage HttpClient instances 655 Creating a basic HttpClient instance 656 Named HttpClient instances 660 Typed HttpClient instances 660 Summary 662 16 Error Handling, Monitoring, and Observability 663 Technical requirements 663 Error handling 663 Handling exceptions 664 Health checks 673 Implementing a basic health check 674 Monitoring and observability 680 What is observability? 681 Summary 715 17 Cloud-Native Patterns 717 Technical requirements 717 Domain-driven design 718 Ubiquitous language 718 Bounded context 719 DDD layers 719 Clean architecture 728 Microservices 729 Web API design patterns 732 CQRS 732 Summary 760 Further reading 760 Index 761 Other Books You May Enjoy 778
Xiaodi Yan / Сяоди Ян - Web API Development with ASP.NET Core 8 / Разработка веб-API с использованием ASP.NET Core 8 [2024, PDF, EPUB, ENG] download torrent for free and without registration
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum You cannot attach files in this forum You can download files in this forum