Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
ASP.NET Core and Vue.js

You're reading from   ASP.NET Core and Vue.js Build real-world, scalable, full-stack applications using Vue.js 3, TypeScript, .NET 5, and Azure

Arrow left icon
Product type Paperback
Published in Jun 2021
Publisher Packt
ISBN-13 9781800206694
Length 478 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Devlin Basilan Duldulao Devlin Basilan Duldulao
Author Profile Icon Devlin Basilan Duldulao
Devlin Basilan Duldulao
Arrow right icon
View More author details
Toc

Table of Contents (25) Chapters Close

Preface 1. Section 1: Getting Started
2. Chapter 1: Getting Started with ASP.NET Core and Vue.js FREE CHAPTER 3. Chapter 2: Setting Up a Development Environment 4. Section 2: Backend Development
5. Chapter 3: Starting Your First ASP.NET Core Project 6. Chapter 4: Applying Clean Architecture to an ASP.NET Core Solution 7. Chapter 5: Setting Up DbContext and Controllers 8. Chapter 6: Diving into CQRS 9. Chapter 7: CQRS in Action 10. Chapter 8: API Versioning and Logging in ASP.NET Core 11. Chapter 9: Securing ASP.NET Core 12. Chapter 10: Performance Enhancement with Redis 13. Section 3: Frontend Development
14. Chapter 11: Vue.js Fundamentals in a Todo App 15. Chapter 12: Using a UI Component Library and Creating Routes and Navigations 16. Chapter 13: Integrating a Vue.js Application with ASP.NET Core 17. Chapter 14: Simplifying State Management with Vuex and Sending GET HTTP Requests 18. Chapter 15: Sending POST, DELETE, and PUT HTTP Requests in Vue.js with Vuex 19. Chapter 16: Adding Authentication in Vue.js 20. Section 4: Testing and Deployment
21. Chapter 17: Input Validations in Forms 22. Chapter 18: Writing Integration Tests Using xUnit 23. Chapter 19: Automatic Deployment Using GitHub Actions and Azure 24. Other Books You May Enjoy

What's new in ASP.NET Core?

Here is a rough list of what has been added to the new ASP.NET Core web framework:

  • Performance Improvements to HTTP/2: .NET 5 improves the performance of HTTP/2 by adding support for HPack dynamic compression of HTTP/2 response headers in Kestrel.
  • Reduction in container image sizes: Sharing layers between two images dramatically reduces the size of the aggregate images that you pull. This reduction is achieved by re-platting the SDK image on the ASP.NET runtime image.
  • Reloadable endpoints via configuration for Kestrel: Kestrel can now observe changes to configurations passed to KestrelServerOptions.Configure. Then it can be applied to any new endpoints without restarting your application.
  • JSON extension methods for HttpRequest and HttpResponse: Using the new ReadFromJsonAsync and WriteAsJsonAsync extension methods, you can now easily consume and use JSON data from HttpRequest and HttpResponse. The JSON extension methods can also be written with an endpoint routing to create JSON APIs like so:
    endpoints.MapGet("/weather/{city:alpha}", 
                     async context =>
    {
        var city = (string)context.Request
                                  .RouteValues["city"];
        var weather = GetFromDatabase(city);
        await context.Response.WriteAsJsonAsync(weather);
    });
  • An extension method allows anonymous access to an endpoint: The AllowAnonymous extension allows anonymous access to an endpoint when using endpoint routing. In the following code, the extension method, AllowAnonymous(), is chained after calling the MapGet method:
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
      app.UseRouting();
      app.UseAuthentication();
      app.UseAuthorization();
      app.UseEndpoints(endpoints =>
     {
      endpoints.MapGet("/", async context =>
      {
       await context.Response
                    .WriteAsync("Hello Packt!");
      }).AllowAnonymous();
     });
    }
  • Custom handling of authorization failures: With the new IAuthorizationMiddlewareResultHandler interface invoked by AuthorizationMiddleware, custom handling of authorization failures is now easier than before. You can now register a custom handler in the dependency injection container that allows developers to customize HTTP responses.
  • SignalR Hub filters: Similar to how middleware lets you run code before and after an HTTP request, Hub Pipelines in ASP.NET SignalR is the feature that allows you to run code before and after Hub methods are called.
  • Updated debugging for Blazor WebAssembly: No need for a VS Code JS debugger extension for developing Blazor WebAssembly apps.
  • Blazor accessibility improvements: Input components that derive from InputBase now automatically render aria-invalid (an HTML validation attribute) on failed validation.
  • Blazor performance improvements: This includes optimized .NET runtime execution, JSON serialization, JavaScript interop, and component rendering.
  • Kestrel socket transport support for additional endpoint types: The System.Net.Sockets transport in Kestrel now allows you to bind to both Unix domain sockets and existing file handles.
  • Azure Active Directory authentication with Microsoft.Identity.Web: Any ASP.NET Core project templates can now easily integrate with Microsoft.Identity.Web to handle authentication with Azure AD.
  • Sending HTTP/2 PING frames: Microsoft added the ability to send periodic PING frames in Kestrel by setting limits on KestrelServerOptions, which are Limits.Http2.KeepAlivePingInterval and Limits.Http2.KeepAlivePingTimeout, as shown in the following code:
    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.ConfigureKestrel(options =>
                {
                    options.Limits.Http2.                KeepAlivePingInterval = TimeSpan
                    .FromSeconds(10);
                    options.Limits.Http2.                KeepAlivePingTimeout = TimeSpan
                    .FromSeconds(1);
                });
                webBuilder.UseStartup<Startup>();
            });
  • Custom header decoding in Kestrel: Microsoft also added the ability to specify which System.Text.Encoding to use to interpret incoming headers based on the header name instead of defaulting to UTF-8, like so:
    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.ConfigureKestrel(options =>
                {
                    options.RequestHeaderEncodingSelector =                 encoding =>
                    {
                        switch (encoding)
                        {
                            case "Host":
                                return System.Text
                                             .Encoding
                                             .Latin1;
                            default:
                                return System.Text
                                             .Encoding
                                             .UTF8;
                        }
                    };
                });
                webBuilder.UseStartup<Startup>();
            });
  • CSS isolation for Blazor components: Blazor now supports scoped CSS styles inside a component.
  • Lazy loading in Blazor WebAssembly: Use the OnNavigateAsunc event on the Router component to lazy load assemblies for a specific page.
  • Set UI focus on Blazor apps: Use the FocusAsync method on ElementReference to set the UI focus on an element.
  • Control Blazor component instantiation: IComponentActivator can be used to control how Blazor components are instantiated.
  • Influencing the HTML head in Blazor apps: Add dynamic link and meta tags by using the built-in Title, Link, and Meta components in the head tags of a Blazor app.
  • Protected browser storage: ProtectedLocalStorage and ProtectedSessionStorage can be used to create a secure persisted app state in local or session storage.
  • Model binding and validation with C#9 record types: You can use Record types to model data transmitted over the network like so:
    public record Person([Required] string Name, 
                         [Range(0, 150)] int Age);
    public class PersonController
    {
       public IActionResult Index() => View();
       [HttpPost]
       public IActionResult Index(Person person)
       {
              // ...
       }
    }

    You can see the record type after the public access modifier.

  • Improvements to DynamicRouteValueTransformer: You can now pass state to DynamicRouteValueTransformer and filter the set of chosen endpoints.
  • Auto-refresh with dotnet watch: The ASP.NET Core project will now both launch the default browser and auto-refresh it as you make changes to your code while running dotnet watch.
  • Console Logger Formatter: The console logger formatter gives the developer complete control over the formatting and colorization of the console output.
  • JSON Console Logger: Microsoft added a built-in JSON formatter that emits structured JSON logs to the console.

That was the list of what's new in ASP.NET Core 5. What about breaking changes? Are there any breaking changes in ASP.NET Core 5? Yes, and let's check them out in the next section.

Breaking changes in migration from ASP.NET Core 3.1 to ASP.NET Core 5.0

If you are planning to migrate your existing app or a project under development in .NET Core 3.1 to Core 5, you might need to take a pause and read the following quick list of breaking changes.

Authentication

There's a new behavior in integrating Azure and ASP.NET Core to determine a user's identity. The AzureAD.UI and AzureADB2C.UI APIs and packages are now obsolete in the framework. AzureAD.UI and AzureADB2C.UI migrated to the Microsoft Authentication Library (or MSAL), which is under Microsoft.Identity.Web.

Authorization

There is a little change in the endpoint routing of ASP.NET Core. The resource passed to the authorization endpoint is now guaranteed to be of the type HttpContext. The new change will allow developers to use the functionalities of HttpContext from non-endpoint routing.

Azure

Azure prefixes replaced the Microsoft prefixes in integration packages. These packages are as follows:

  • Microsoft.Extensions.Configuration.AzureKeyVault, which developers use to connect Azure Key Vault to the configuration system.
  • Microsoft.AspNetCore.DataProtection.AzureKeyVault, which connects Azure Key Vault to the ASP.NET Core data protection system.
  • Microsoft.AspNetCore.DataProtection.AzureStorage, which lets developers port Azure Blob storage into the ASP.NET Core data protection system.

Blazor

This new framework for browser-based .NET apps of Microsoft has some recent changes:

  • The compiler will trim any whitespaces in components of Blazor during compile time. Trimming of the compiler improves the performance of rendering and DOM diffing, which is comparing the previous version of the virtual DOM to the new version of the virtual DOM.
  • The ProtectedBrowserStorage feature is now part of the ASP.NET Core shared framework for a better developer experience. The shared frameworks are Microsoft.NETCore.App, Microsoft.AspNetCore.App, and Microsoft.AspNetCore.All.
  • .NET 5.0 is the new target framework of Blazor Server and Blazor WebAssembly projects to better align with .NET target framework requirements.

HTTP

There are some changes in how you would handle bad HTTP request exceptions and log HTTP requests and responses:

  • Microsoft.AspNetCore.Http.BadHttpRequestException is the new derived class of Microsoft.AspNetCore.Server.Kestrel.BadHttpRequestException and Microsoft.AspNetCore.Server.IIS.BadHttpRequestException. These packages are tagged as obsolete and are set for removal in the future release to consolidate duplicate types and to unify the packages across server implementations.
  • Code as integers is now the status code used by the IHttpClientFactory interface to log HTTP instead of names, to offer developers more flexibility on querying ranges of values.

Kestrel

Here are the changes to Kestrel, the cross-platform web server for ASP.NET Core:

  • SslProtocols.None is now the default TLS protocol version of HttpsConnectionAdapterOptions.SslProtocols instead of SslProtocols.Tls12 | SslProtocols.Tls11, to support TLS 1.3 and future versions by default.
  • Since socket-based transport was the default transport of Kestrel, the libuv APIs are now tagged as obsolete and will be removed in the next version.

Middleware

The middleware, which is a pipeline to handle requests and responses, has a new behavior. DatabaseErrorPageMiddleware and its related extensions are marked as obsolete and replaced with DatabaseDeveloperPageExceptionFilter.

SignalR

The SignalR library, which uses real-time web functionality in an application, has a couple of changes:

  • ASP.NET Core 5.0 upgrades the package version of the MessagePack hub protocol from 1.x to 2.x, which has the latest improvements.
  • The UseSignalR and UseConnections methods are no longer available because they had custom logic that didn't interact with other routing components in ASP.NET Core.

Static files

Serving text/csv, a static file, directly to client applications has a new header value. text/csv replaced application/octet-stream as the Content-Type header value of Static File Middleware for .csv files for compliance with the RFC 7111 standard. You can find the full details of the RFC 7111 standard at https://tools.ietf.org/html/rfc7111#section-5.1.

When to use ASP.NET Core

Since ASP.NET Core provides a web framework that can be used in different use-case scenarios, you can use the framework to build dynamic web applications. This includes web applications such as online stores, internal enterprise apps, content-base, multi-tenant applications, Content Management Systems (CMSes), Software as a Service (SaaS), or just a RESTful service with ASP.NET Core. We will be focusing on building a RESTful service in ASP.NET Core because this is the backend that we will integrate with the Vue.js application in the third part of the book.

ASP.NET Core also contains features for managing authentication, authorization, data protection, HTTPS enforcement, app secrets, XSRF/CSRF prevention, CORS management, and enabling developers to build robust yet secure ASP.NET Core apps.

Why should you learn ASP.NET Core?

Aside from ASP.NET Core's performance, ASP.NET Core is a popular choice with enterprise businesses, insurance, banks, and other types of businesses. Using IT JobsWatch (https://www.itjobswatch.co.uk/), you can search jobs by date in 2020. The .NET Core job vacancy trend has been increasing since 2019, and with average earnings of $95,657/year according to ZipRecruiter (https://www.ziprecruiter.co.uk/).

Based on Stackoverflow's 2020 survey (https://insights.stackoverflow.com/survey/2020), ASP.NET Core is the winner of their most loved and wanted web framework. It received the highest number of votes, which went up to 70.7%, meaning these are the developers who are developing with specific languages or technologies and have shown interest in continuing to create with it, followed by React, Vue, and Express. These are reasons to try and use ASP.NET Core because of the huge availability of jobs, and ASP.NET Core is here to stay for the next several years.

This completes the quick overview of ASP.NET Core and what is new in ASP.NET Core 5. You have learned about the current state of ASP.NET Core and how it is the right choice for building performant RESTful services. Now it is time to meet Vue.js.

Let's see why, suddenly, Vue.js became one of the hottest JavaScript frameworks.

You have been reading a chapter from
ASP.NET Core and Vue.js
Published in: Jun 2021
Publisher: Packt
ISBN-13: 9781800206694
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image