title
stringlengths
3
46
content
stringlengths
0
1.6k
17:891
.AddDataAnnotationsLocalization();
17:892
17:893
Resource files for data annotations applied to a class whose full name is, say, MyWebApplication.ViewModels.Account.RegisterViewModel must have the following path:
17:894
{ResourcesPath}/ViewModels/Account/RegisterViewModel.{culture name}.resx
17:895
17:896
It is worth pointing out that the first segment of the namespace that corresponds to the .dll application name is replaced with ResourcesPath. If ResourcesPath is empty and you use the default namespaces created by Visual Studio, then the resource files must be placed in the same folder that contains the classes they are associated with.
17:897
It is possible to localize strings and HTML fragments in controllers, or wherever dependencies can be injected, by associating each group of resource files with a type, such as MyType, and then injecting either IHtmlLocalizer<MyType> for HTML fragments or IStringLocalizer<MyType> for strings that need to be HTML-encoded.
17:898
Their usage is identical to the usage of IViewLocalizer. The path of the resource files associated with MyType is computed, as in the case of data annotations. If you would like to use a unique group of resource files for the whole application, a common choice is to use the Startup class as the reference type (IStringLocalizer<Startup> and IHtmlLocalizer<Startup>). Another common choice is to create various empty classes to use as reference types for various groups of resource files.
17:899
Now that we’ve learned how to manage globalization in our ASP.NET Core projects, in the next subsection, we will describe the more important pattern used by ASP.NET Core MVC to enforce a separation of concerns: the MVC pattern itself.
17:900
The MVC pattern
17:901
MVC is a pattern used to implement the presentation layers of a web application. The basic idea is to apply a Separation of Concerns between the logic of the presentation layer and its graphics. Logic is taken care of by controllers, while graphics are factored out into views. Controllers and views communicate through the model, which is often called the ViewModel to distinguish it from the models of the business and data layers.
17:902
It is worth pointing out that the original definition of the MVC pattern proposes directly the use of domain models instead of ViewModels, but then, most of the MVC web frameworks started using the concept of ViewModel because specifying the information to render in a view requires just a projection of the original domain model (just some model data possibly organized in a different way) and often additional data, such as, for instance, the items per page of a pager, and the items required by the type input selected.
17:903
However, what is the logic of a presentation layer? In Chapter 1, Understanding the Importance of Software Architecture, we saw that software requirements can be documented with use cases that describe the interaction between the user and the system.
17:904
Roughly speaking, the logic of the presentation layer consists of the management of use cases; hence, roughly, use cases are mapped to controllers, and every single operation of a use case is mapped to an action method of those controllers. Hence, controllers take care of managing the protocol of interaction with the user and rely on the business layer for any business processing involved during each operation.
17:905
Each action method receives data from the user, performs some business processing, and, depending on the results of this processing, decides what to show to the user and encodes it in the ViewModel. Views receive ViewModels that describe what to show to the user and decide the graphics to use, that is, the HTML to use.
17:906
What are the advantages of separating the logic and user interface into two different components? The main advantages are listed here:
17:907
17:908
Changes in graphics do not affect the remainder of the code, so you can experiment with various user interface elements to optimize the interaction with the user, without putting the reliability of the remainder of the code at risk.
17:909
The application can be tested by instantiating controllers and passing the parameters, with no need to use testing tools that operate on the browser pages. In this way, tests are easier to implement. Moreover, they do not depend on the way graphics are implemented, so they do not need to be updated each time the graphics change.
17:910
It is easier to split the job between developers who implement controllers and graphic designers who implement views. Often, graphic designers have difficulties with Razor, so they might just furnish an example HTML page that developers transform into Razor views that operate on the actual data.
17:911
17:912
For an example of how to put into practice the general principles discussed above, please refer to the A frontend microservice section in Chapter 21, Case Study, but it is better to read Chapter 18, Implementing Frontend Microservices with ASP.NET Core, beforehand. There, we’ll look at how to create a frontend microservice with ASP.NET Core MVC.
17:913
Summary
17:914
In this chapter, we analyzed the ASP.NET Core pipeline and various modules that comprise an ASP.NET Core MVC application in detail, such as authentication/authorization, the options framework, and routing. Then, we described how controllers and Views map requests to the response HTML. We also analyzed all the improvements introduced in the latest versions.
17:915
Finally, we analyzed all the design patterns implemented in the ASP.NET Core MVC framework and, in particular, the importance of the Separation of Concerns principle and how ASP.NET Core MVC implements it in the ASP.NET Core pipeline, as well as in its validation and globalization modules. We focused in more detail on the importance of a Separation of Concerns between the presentation layer logic and graphics, as well as how the MVC pattern ensures it.
17:916
You can find a full example of how to use ASP.NET Core MVC in the next chapter, which deals with frontend microservices and describes a complete frontend microservice, whose presentation layer uses ASP.NET Core MVC.
17:917
Questions
17:918
17:919
Can you list all the middleware modules scaffolded by Visual Studio in an ASP.NET Core project?
17:920
Does the ASP.NET Core pipeline module need to inherit from a base class or implement some interface?
17:921
Is it true that a tag must have just one tag helper defined for it, as, otherwise, an exception is thrown?
17:922
Do you remember how to test if validation errors have occurred in a controller?
17:923
What is the instruction in a layout view for including the output of the main view?
17:924
How are secondary sections of the main view invoked in a layout view?
17:925
How does a controller invoke a view?
17:926
By default, how many providers are installed in the globalization module?
17:927
Are ViewModels the only way for controllers to communicate with their invoked views?
17:928
17:929
Further reading
17:930
17:931
More details on the ASP.NET Core and ASP.NET Core MVC framework are available in its official documentation at https://docs.microsoft.com/en-US/aspnet/core/.
17:932
More details on the Razor syntax can be found at https://docs.microsoft.com/en-us/aspnet/core/razor-pages/?tabs=visual-studio.
17:933
How to model bind collections and dictionaries is explained in this excellent Phil Haack post: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx.
17:934
Documentation on the creation of custom tag helpers that were not discussed in this chapter can be found at https://docs.microsoft.com/en-US/aspnet/core/mvc/views/tag-helpers/authoring.
17:935
Documentation on the creation of custom controller attributes can be found at https://docs.microsoft.com/en-US/aspnet/core/mvc/controllers/filters.
17:936
The definition of custom validation attributes is discussed in this article: https://blogs.msdn.microsoft.com/mvpawardprogram/2017/01/03/asp-net-core-mvc/
17:937
17:938
Learn more on Discord
17:939
To join the Discord community for this book – where you can share feedback, ask questions to the authors, and learn about new releases – follow the QR code below:
17:940
https://packt.link/SoftwareArchitectureCSharp12Dotnet8
17:941
17:942
17:943
18:1
Implementing Frontend Microservices with ASP.NET Core
18:2
Chapter 14, Implementing Microservices with .NET, described general techniques for implementing microservices in .NET but focused mainly on worker microservices, that is, on microservices that perform background jobs without communicating with anything outside of the application.
18:3
Microservices that communicate with the world outside of the application bring with them other problems and need further techniques.
18:4
18:5
More specifically, microservices that communicate with a human user must implement a presentation layer, while microservices that expose APIs must conform to well-established standards and should preferably have documentation. Moreover, web APIs that target single-page applications (SPAs) must conform with browser policies; that is, either they are exposed on a single domain that is the same domain the SPA was downloaded from, or they must configure CORS policies. We will see how to address both CORS and issues due to browser policies in Chapter 19, Client Frameworks: Blazor.
18:6
18:7
Worth mentioning also are all the challenges brought by any presentation layer, that is, ensuring a fast and effective interaction with the user and managing the state of the interaction with the user with maintainable code without falling into spaghetti code. General usability problems and solutions were discussed in Chapter 2, Non-Functional Requirements. We will discuss more technology-specific usability and status management problems in this chapter and in Chapter 19, Client Frameworks: Blazor.
18:8
Finally, all front end microservices must put solid security policies in place to defend the application from hackers. Some techniques are common to both front-ends and web APIs and are automatically handled by all major web servers, such as countermeasures against path-transversal attacks and denial of service. Others, instead, are specific to HTML pages, such as forgery. ASP.NET Core MVC defenses against forgery are discussed in the Chapter 21, Case study.
18:9
Techniques for implementing public self-documented web APIs were described in Chapter 15, Applying Service-Oriented Architectures with .NET, while techniques for implementing server-based presentation layers were covered in Chapter 17, Presenting ASP.NET Core, and techniques for implementing client-based presentation layers will be covered in Chapter 19, Client Frameworks: Blazor. Moreover, general techniques for implementing microservices were covered in Chapter 11, Applying a Microservice Architecture to Your Enterprise Application, Chapter 7, Understanding the Different Domains in Software Solutions, and Chapter 14, Implementing Microservices with .NET.
18:10
Therefore, in this chapter, after a short section about concepts and techniques specific to front-end microservices, we will show you how to put all these concepts and techniques together in the practical implementation of a front-end microservice. More specifically, we will discuss various implementation options and how to architect the whole layer structure of a front-end microservice. A complete example that shows how all layers of a front-end microservice work together, in practice, is described in the A frontend microservice section of Chapter 21, Case Study.
18:11
More specifically, this chapter covers the following topics:
18:12
18:13
Front-ends and micro-frontends
18:14
Defining the domain layer interface
18:15
Defining the domain layer implementation
18:16
Defining the application layer
18:17
Defining controllers
18:18
18:19
We will use the onion architecture and the patterns described in Chapter 7, Understanding the Different Domains in Software Solutions.
18:20
Technical requirements
18:21
This chapter requires the free Visual Studio 2022 Community edition or better with all database tools installed.
18:22
The code samples necessary to clarify the concepts in this chapter will be taken from a practical example application based on the WWTravelClub book use case. The full example application is described in detail in the A front end microservice section of Chapter 21, Case Study. Its code is available at https://github.com/PacktPublishing/Software-Architecture-with-C-Sharp-12-and-.NET-8-4E.
18:23
Front-ends and micro-frontends
18:24
The main peculiarity of front-end microservices is that they need a robust web server that is able to optimize all the request/response handling and ensure the needed level of security. Moreover, high-traffic applications also need a load balancer.
18:25
Examples of services offered by robust web servers like IIS, Apache, and NGINX are:
18:26
18:27
Limiting access to just some file types and directories to prevent access to private files and to prevent remote file execution; that is, execution of server commands/scripts through web requests.
18:28
Blocking dangerous requests that might cause access to unwanted files or directories (path-traversal attacks).
18:29
Blocking requests that exceed a customizable length since they might cause a denial of service.
18:30
Logging and IP address blocking to discover and contrast hacker attacks.
18:31
Redirecting requests to the application associated with each URL.
18:32
Queueing requests and assigning them to available threads. This capability is fundamental for performance optimization since executing too many requests compared to the available processor cores might cause unacceptable performance.
18:33
Ensuring the isolation of applications running on the same process but in different threads and more.
18:34
18:35
If the front-end service is hosted on a Kubernetes cluster, both an adequate web server and load balancing can be provided through an Ingress.
18:36
Otherwise, Azure App Service (see the Further reading section) might be a good option since it offers a scalable level of load balancing, excellent security, monitoring services, and so on.
18:37
A front-end microservice doesn’t need to interface directly with anything outside of an application. In fact, in micro-frontend architectures, there is no unique front-end, but the role of the front-end is split among several microservices. In these architectures, typically, the role of directing traffic toward the right front-end and/or of combining several responses into a unique response is taken by an interface front-end that is load-balanced and carries the burden of ensuring the right level of security.
18:38
The reasons for using micro-frontends are the same as the ones for using other microservices. We discussed them in detail in Chapter 11, Applying a Microservice Architecture to Your Enterprise Application, but it is worth repeating the more important ones here:
18:39
18:40
Optimizing the usage of hardware resources by scaling just the microservices that need more resources
18:41
Having independent software lifecycles for each microservice, so each microservice can evolve independently from the others to match the user needs and so that each microservices developer team can work independently from the others
18:42
18:43
Micro-frontend architectures use quite different techniques for HTML websites, like ASP.NET Core MVC websites, and for web APIs. Actually, the word “micro-frontend” is used just with HTML websites/SPAs, while web APIs exposed to the outside world are referred to as public web APIs. We will describe public web APIs and HTML micro-frontends and the techniques they use in two dedicated subsections, starting with public web APIs.
18:44
Public web APIs
18:45
In the case of web APIs, all microservices are accessible through a unique load-balanced piece of software called an API gateway that sits in between the clients and the various API services. The basic role of an API gateway is to make the whole API accessible from a unique domain to both avoid problems with the browser’s unique domain policy and make the usage of all API services simpler.
18:46
18:47
Figure 18.1: API gateway