title
stringlengths 3
46
| content
stringlengths 0
1.6k
|
---|---|
Index:915 | Follow these simple steps to get the benefits: |
Index:916 | |
Index:917 | Scan the QR code or visit the link below. |
Index:918 | |
Index:919 | |
Index:920 | https://packt.link/free-ebook/9781805127659 |
Index:921 | |
Index:922 | Submit your proof of purchase. |
Index:923 | That’s it! We’ll send your free PDF and other benefits to your email directly. |
Index:924 | |
Index:925 | |
Index:926 | |
17:1 | Presenting ASP.NET Core |
17:2 | In this chapter, you will learn how to implement a web application and a web-based presentation layer. More specifically, you will learn about ASP.NET Core and how to implement a web application presentation layer based on ASP.NET Core MVC. |
17:3 | ASP.NET Core is a .NET framework for implementing web applications. The ASP.NET Core Web API was partially described in previous chapters, so this chapter will focus mainly on ASP.NET Core in general and on ASP.NET Core MVC. More specifically, this chapter will cover the following topics: |
17:4 | |
17:5 | Understanding the presentation layers of web applications |
17:6 | Understanding the basics of ASP.NET Core |
17:7 | Understanding how ASP.NET Core MVC creates the response HTML |
17:8 | Understanding the connection between ASP.NET Core MVC and design principles |
17:9 | |
17:10 | We will review and provide further details on the structure of the ASP.NET Core framework, which we discussed in part in earlier chapters. Here, the main focus is on how to implement web-based presentation layers based on the so-called Model View Controller (MVC) architectural pattern. |
17:11 | We will also analyze how server-side HTML is created with ASP.NET Core MVC’s Razor template language. |
17:12 | Each concept is explained using code examples, and Chapter 18, Implementing Frontend Microservices with ASP.NET Core, is dedicated to the description of a frontend microservice implemented with ASP.NET Core MVC. For a complete practical example of how to put into practice the general principles discussed in this and the next chapter, please refer to the A frontend microservice section in Chapter 21, Case Study. |
17:13 | Technical requirements |
17:14 | This chapter requires the free Visual Studio 2022 Community edition, ideally with all the database tools installed. |
17:15 | Understanding the presentation layers of web applications |
17:16 | This chapter discusses an architecture for implementing the presentation layers of web applications based on the ASP.NET Core framework. The presentation layers of web applications are based on three techniques: |
17:17 | |
17:18 | Mobile or desktop native applications that exchange data with servers through REST or SOAP services: We will discuss desktop applications in Chapter 19, Client Frameworks: Blazor. |
17:19 | Single-Page Applications (SPAs): These are HTML-based applications whose dynamic HTML is created on the client, either in JavaScript or with the help of WebAssembly (a kind of cross-browser assembly that can be used as a high-performance alternative to JavaScript). Like native applications, SPAs exchange data with the server through HTTP-based APIs, but they have the advantage of being independent of the device and its operating system, since they run in a browser. Chapter 19, Client Frameworks: Blazor, describes the Blazor SPA framework, which is based on WebAssembly, since it is based itself on a .NET runtime compiled in WebAssembly. |
17:20 | HTML pages created by the server whose content depends on the data to be shown to the user: The ASP.NET Core MVC framework, which will be discussed in this chapter, is a framework for creating such dynamic HTML pages. |
17:21 | |
17:22 | The remainder of this chapter focuses on how to create HTML pages on the server side and, more specifically, on ASP.NET Core MVC. |
17:23 | Understanding the basics of ASP.NET Core |
17:24 | ASP.NET Core is based on the concept of the generic host, as explained in the Using generic hosts subsection of Chapter 11, Applying a Microservice Architecture to Your Enterprise Application. The basic architecture of ASP.NET Core was outlined in the A short introduction to ASP.NET Core subsection of Chapter 15, Applying Service-Oriented Architectures with .NET. |
17:25 | It is worth remembering that the host configuration consists mainly of adding services to the Dependency Injection (DI) engine through the Services property of a host builder instance, whose type implements the IServiceCollection interface: |
17:26 | var builder = WebApplication.CreateBuilder(args); |
17:27 | // Add services to the container. |
17:28 | builder.Services.AddTransient<IMyService, MyService>(); |
17:29 | ... |
17:30 | // Add services to the container through extension methods. |
17:31 | builder.Services.AddControllersWithViews(); |
17:32 | builder.Services.AddAllQueries(typeof(ManagePackagesController).Assembly); |
17:33 | ... |
17:34 | ... |
17:35 | var app = builder.Build(); |
17:36 | |
17:37 | The IServiceCollection interface implemented by builder.Services defines all the services that can be injected into object constructors through DI. |
17:38 | Services can be defined either by calling the various overloads of AddTransient and AddSingleton directly in Program.cs, or by grouping these calls in some IServiceCollection extension methods, which are then called in Program.cs. The way services are handled in .NET is explained in detail in the Using generic hosts section of Chapter 11. Here, it is worth pointing out that, together with singleton and transient services, ASP.NET Core also supports another kind of service lifetime, session lifetime, which is the lifetime of a single web request served by the ASP.NET Core application. Session-scoped services are declared with AddScoped overloads that are completely analogous to the overloads of AddTransient and AddSingleton. |
17:39 | Session-scoped services are useful for storing data that are specific to a single request that must be used throughout the whole request by several application components. A typical example of a .NET session-scoped service is the Entity Framework Core DBContexts. In fact, all operations performed on the various aggregates involved in the request must use the same request-specific DBContext so that all changes can be saved to the database in a single transaction, with a unique SaveChanges operation. |
17:40 | Practical applications of session-scoped DBContexts and other services are described in more detail in Chapter 18, Implementing Frontend Microservices with ASP.NET Core. |
17:41 | Usually, all applications define most of the application configuration through the host builder so that after the host is built with var app = builder.Build(), you need to call app.Run() or await app.RunAsync() to launch the application. |
17:42 | The ASP.NET Core host instead performs another configuration step after it has been built; it defines the so-called ASP.NET Core HTTP request processing pipeline, which will be described in more detail in the next subsection. |
17:43 | ASP.NET Core middleware |
17:44 | ASP.NET Core contains an internal web server called Kestrel that has just the basic web server functionalities. So in simple applications such as IoT applications, or worker microservices, we can avoid the overhead of a fully optional complex web server like IIS, Apache, or NGINX. |
17:45 | If ASP.NET Core is used to implement the application layer of a frontend microservice/application or a classic website, Kestrel can be interfaced with all major web servers that proxy their request to Kestrel. |
17:46 | In version 8, by default, Kestrel supports all protocols up to and including version HTTP/3. |
17:47 | In turn, Kestrel passes all requests to a set of configurable modules that you can assemble according to your needs. Each module takes care of a functionality that you may or may not need. Examples of such functionalities include authorization, authentication, static file processing, protocol negotiation, and CORS handling. Since most of the modules apply transformations to the incoming request and the final response, these modules are usually referred to as middleware. |
17:48 | You can put together all the middleware modules you need by inserting them into a common processing framework called the ASP.NET Core pipeline. |
17:49 | More specifically, ASP.NET Core requests are processed by pushing a context object through a pipeline of ASP.NET Core modules, as shown in the following diagram: |
17:50 | |
17:51 | Figure 17.1: ASP.NET Core pipeline |
17:52 | The object that is inserted into the pipeline is an HttpContext instance that contains the data of the incoming request. More specifically, the Request property of HttpContext contains an HttpRequest object whose properties represent the incoming request in a structured way. There are properties for headers, cookies, the request path, parameters, form fields, and the request body. |
17:53 | The various modules can contribute to the construction of the final response that is written in an HttpResponse object, contained in the Response property of the HttpContext instance. The HttpResponse class is similar to the HttpRequest class, but its properties refer to the response being built. |
17:54 | Some modules can build an intermediate data structure that is then used by other modules in the pipeline. In general, such intermediary data can be stored in custom entries of the IDictionary<object, object>, which is contained in the Items property of the HttpContext object. However, there is a predefined property, User, that contains information about the currently logged-in user. The logged-in user is not computed automatically, so it must be computed by an authentication module. The ASP.NET Core service authorization subsection of Chapter 15, Applying Service-Oriented Architectures with .NET, explained how to add the standard module that performs JWT-based authentication into the ASP.NET Core pipeline. |
17:55 | HttpContext also has a Connection property that contains information on the underlying connection established with the client, as well as a WebSockets property that contains information on possible WebSocket-based connections established with the clients. |
17:56 | HttpContext also has a Features property that contains IDictionary<Type, object>, which specifies the features supported by the web server that hosts the web application and by the pipeline. Features can be set using the .Set<TFeature>(TFeature o) method and retrieved using the .Get<TFeature>() method. |
17:57 | Web server features are automatically added by the framework, while all other features are added by pipeline modules when they process HttpContext. |
17:58 | HttpContext also gives us access to the DI engine through its RequestServices property. You can get an instance of a type managed by the dependency engine by calling the .RequestServices.GetService(Type t) method or, even better, the .GetRequiredService<TService>() extension method that is built on top of it. |
17:59 | However, as we will see in the remainder of this chapter, all types managed by the DI engine are usually automatically injected into constructors, so these methods are only used when we’re building custom middleware or other customizations of the ASP.NET Core engine. |
17:60 | The HttpContext instance that is created for processing a web request is not only available to modules but also to the application code, through DI. It is sufficient to insert an IHttpContextAccessor parameter into the constructor of a class that is automatically dependency injected, and then access its HttpContext property. All controllers that inherit from Controller or ControllerBase (see later in this section) expose an HttpContext property that contains the request HttpContext. |
17:61 | A middleware module is any class with the following structure: |
17:62 | public class CoreMiddleware |
17:63 | { |
17:64 | private readonly RequestDelegate _next; |
17:65 | public CoreMiddleware(RequestDelegate next, ILoggerFactory |
17:66 | loggerFactory) |
17:67 | { |
17:68 | ... |
17:69 | _next = next; |
17:70 | ... |
17:71 | } |
17:72 | public async Task InvokeAsync(HttpContext context) |
17:73 | { |
17:74 | /* |
17:75 | Insert here the module specific code that processes the |
17:76 | HttpContext instance before it is passed to the next |
17:77 | module. |
17:78 | */ |
17:79 | await _next.Invoke(context); |
17:80 | /* |
17:81 | Insert here other module specific code that processes the |
17:82 | HttpContext instance, after all modules that follow this |
17:83 | module finished their processing. |
17:84 | */ |
17:85 | } |
17:86 | } |
17:87 | |
17:88 | It is also possible to pass InvokeAsync directly as a lambda to app.Use, as shown here: |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.