ASP.NET Core updates in .NET 8 Preview 1

Table of Contents

Full stack web UI using Blazor

Improved authentication and authorization experience

Native AOT

ASP.NET Core Roadmap for .NET 8

What’s new in .NET 8 Preview 1?

start

Upgrade an existing project

routing tools

Routing constraint performance improvements

New analyzer for API development

It is recommended to set or append to the title dictionary instead of adding

Warn if the parameter type passed to a route handler does not implement the correct interface

Detect if RequestDelegate is not implemented correctly

Send exception to Blazor’s SynchronizationContext

Hot reload supports .NET instance fields, properties and events on WebAssembly

Support symbol servers when debugging .NET on WebAssembly

Blazor WebAssembly debugging in Firefox

Experimental Webcil format for .NET assemblies

Specify the initial URL of the BlazorWebView to load

New option to keep SPA development server running

Support named pipes in Kestrel

HTTP/3 enabled by default

HTTP/2 over TLS (HTTPS) support on macOS

gRPC JSON transcoding no longer requires http.proto and annotations.proto

Specify server timeout and keep-alive interval settings using HubConnectionBuilder

IPNetwork.Parse and TryParse

IPv4

IPv6

HTTP_PORTS and HTTPS_PORTS configuration support

Warning when the specified HTTP protocol is not used

Provide feedback


.NET 8 Preview 1 is now available! This is the first preview of the next major version of .NET, which will include the next wave of innovations in web development with ASP.NET Core.

In .NET 8, we plan to make broad investments across ASP.NET Core. Here are some areas we plan to focus on:

UsingBlazor Full StackWeb UI

Note: This section was previously titled “Blazor United,” but to avoid confusion we no longer use that name. Instead, we’ll focus on the new features and enhancements added to Blazor in .NET 8 for full-stack web UI development.

In ASP.NET Core today, we have a few different ways to build web UIs:

  • MVC & Razor Pages: The framework uses server-side rendering (SSR) to dynamically generate HTML from the server in response to requests. Rendering from the server helps your application load quickly because all the hard work of getting the data and deciding how to display it is already done on the server – the client only needs to display the HTML that has been rendered. They can leverage powerful server hardware to directly access back-end data and services.
  • Blazor: Blazor’s component model focuses on handling UI interaction. Server-side rendering requires every UI interaction to be sent to the server, so it is not suitable for rich interactive UIs. For rich interactivity you need to use client-side rendering (CSR), which has much lower latency and allows easy access to client-side functionality.

Many modern web applications require a combination of these methods, including server-side rendering and client-side rendering. Perhaps your homepage or blog is best handled using server-side rendering so that it loads quickly and is easily indexed, while the app’s more complex features require the responsiveness of running from the client side. Currently, for .NET, this requires using several different frameworks simultaneously: MVC, Razor Pages, and Blazor.

In .NET 8, we’re working to merge the benefits of server-side and client-side rendering into a single full-stack programming model based on Blazor. With Blazor in .NET 8, you can use a single Blazor-based architecture for server-side rendering and full client-side interaction with Blazor Server or WebAssembly. All in one project, with the ability to easily switch between different rendering modes or even mix them within the same page. Blazor in .NET 8 will also enable new rendering features such as streaming rendering and progressive enhancements for navigation and form posts.

Check out the following early prototype video, which demonstrates many of these new features in action:

Related GitHub issue: dotnet/aspnetcore#46636

Improved authentication and authorization experience

In some cases, authentication and authorization can be difficult to implement in ASP.NET Core applications. In .NET 8, our goals are:

  • Create a simple, intuitive, and well-documented experience for authentication and authorization using the web that is easy to develop and test.
  • Provides a clear set of steps and tools to support deployment to production.
  • Provide meaningful diagnostics to help resolve security issues quickly and effectively.

NativeAOT

.NET 7 introduces support for publishing .NET console projects as native AOT, resulting in a standalone, platform-specific executable without any runtime JIT. Native AOT apps launch very quickly and use less memory. Applications can be deployed to machines or containers that do not have any .NET runtime installed. In .NET 8, we will extend support for native AOT to ASP.NET Core, starting with cloud-centric API apps built with minimal APIs that meet concerns about published file size, startup time, job set and throughput performance expectations.

Related GitHub issue: dotnet/aspnetcore#45910

.NET 8ASP.NET CoreRoadmap

In addition to the above topics, we have many additional improvements planned in ASP.NET Core. You can find a complete list of ASP.NET Core work planned for .NET 8 in the .NET 8 ASP.NET Core roadmap on GitHub.

.NET 8Preview What’s new in version1?

.NET 8 Preview 1 is the first of many .NET 8 previews in preparation for the August 2023 release of .NET.

Here is a summary of what’s new in ASP.NET Core in this preview:

  • Routing tools
  • Routing constraint performance improvements
  • New analyzer for API development
  • Send exceptions to Blazor’s SynchronizationContext
  • Hot reload supports .NET instance fields, properties and events on WebAssembly
  • Support symbol server when debugging .NET on WebAssembly
  • Blazor WebAssembly debugging in Firefox
  • Experimental Webcil format for .NET assemblies
  • Specify the initial URL of BlazorWebView to load
  • New option to keep SPA development server running
  • Support named pipes in Kestrel
  • HTTP/3 is enabled by default
  • HTTP/2 over TLS (HTTPS) support on macOS
  • gRPC JSON transcoding no longer requires http.proto and annotations.proto
  • Specify server timeout and use HubConnectionBuilder to keep alive interval settings
  • IPNetwork.Parse and TryParse
  • HTTP_PORTS and HTTPS_PORTS configuration support
  • Warning when the specified HTTP protocol is not used

Start

To start using ASP.NET Core in .NET 8 Preview 1, install the .NET 8 SDK.

If you are using Visual Studio, we recommend installing the latest Visual Studio 2022 preview. Visual Studio for Mac support for .NET 8 preview is not available yet, but is coming soon.

Upgrade existing project

To upgrade an existing ASP.NET Core app from .NET 7 to .NET 8 Preview 1, do the following:

  • Update the application’s target framework to net8.0.
  • Update all Microsoft.AspNetCore.* package references to 8.0.0-preview.1.*.
  • Update all Microsoft.Extensions.* package references to 8.0.0-preview.1.*.

Also see the complete list of breaking changes in ASP.NET Core for .NET 8.

Routing Tool

ASP.NET Core is built on routing. Minimal API, Web API, Razor Pages, and Blazor all use routing to customize how HTTP requests are mapped to code.

In .NET 8, we’ve invested in a new set of features to make routing easier to learn and use. These include:

  • Route syntax highlighting
  • Autocomplete parameters and route names
  • Automatically complete routing constraints
  • Route analyzer and fixes
  • Supports minimal API, Web API and Blazor

Grouped together, we call these new features Path Tools. The routing tool is built on Roslyn and has features that light up automatically depending on the IDE you are using. Please try it out in Preview 1 and give us feedback. A blog post introducing the cool new features of the Directions tool is coming soon.

?

Routing constraint performance improvement

ASP.NET Core routing is a powerful, high-performance technology used by almost all ASP.NET Core applications. A common feature of routing is routing constraints. The app uses routing constraints to match requests to the correct endpoint:

// Endpoint only matches requests with a URL slug. For example: article/my-article-name
app.MapGet("article/{name:regex(^[a-z0-9] + (?:-[a-z0-9] + )*$)}", (string name) => { /* . .. */ });

In .NET 8, we’ve made several performance improvements to constraints:

  • Regular expression constraints are now compiled. Creating compiled regular expressions has a one-time cost at startup, but they maximize runtime performance.
  • Duplicate constraints are now shared between routes. Shared cache constraints reduce startup time and memory usage, especially for applications with many routing and regular expression constraints.
  • Alpha constraints now use source-generated regular expressions.

forAPINew analyzer developed

High-quality code is easier to debug, test, and repair. In .NET 8, we’re investing in a set of profilers that will help you leverage ASP.NET Core’s APIs more efficiently. Starting with Preview 1, you can take advantage of new analyzers:

The IHeaderDictionary.Add API will be raised if duplicate keys are added. Typically, you need to set, replace, or append to the header using an indexer or the IHeaderDictionary.Append API. This analyzer warns about usage of the IHeaderDictionary.Add API and provides recommended code fixes that leverage the indexer or Append API.

var context = new DefaultHttpContext();

context.Request.Headers.Add("Accept", "text/html"); // ASP0019 warning
context.Request.Headers["Accept"] = "text/html"; // Apply codefix using indexer
context.Request.Headers.Append("Accept", "text/html"); // Apply codefix using IHeaderDictionary.Append

Thanks to community member @david-acker for his contribution!

If passed to route handler If the parameter type does not implement the correct interface, a warning will be issued

The minimal API supports simple binding from HttpContext elements using rules defined in an implementation of TryParse or BindAsync types. These implementations must conform to specific signatures in order to be exploited by binding logic in the framework. Starting with .NET 8, you will receive a warning if you use a type that does not implement the corresponding interface.

For example, the following code example will trigger a warning because the Customer type does not implement the BindAsync method with the appropriate signature.

var app = WebApplication.Create();

app.MapGet("/customers/{customer}", (Customer customer) => {}); // ASP0021 warning

public classCustomer
{
    public async static Task<Customer> BindAsync(HttpContext context) => new Customer();
}

Detect whetherRequestDelegateis not implemented correctly Correct implementation

RequestDelegate implements an HttpContext and returns a Task. Because Task is the base type of Task, generic variance means you can write code like this:

var app = WebApplication.Create();

Task<string> HelloWorld(HttpContext c)
  => Task.FromResult("Hello " + c.Request.RouteValues["name"]); // ASP0016 warning

app.MapGet("/", HelloWorld);

However, the string response will be discarded at runtime. In .NET 8, a warning will be generated for the above scenario, which can be resolved by making the following code changes:

var app = WebApplication.Create();

Task HelloWorld(HttpContext c) => c.Response.WriteAsync("Hello " + c.Request.RouteValues["name"]);
app.MapGet("/", HelloWorld);

Or take advantage of the minimal API:

var app = WebApplication.Create();

app.MapGet("/{name}", (string name) => $"Hello {name}");

We would also like to thank community member @Youssef1313 for submitting a series of quality improvements and bug fixes to our existing analyzer!

Send exceptions toBlazor< strong>SynchronizationContext

Exceptions can now be dispatched to Blazor’s SynchronizationContext using the new DispatchExceptionAsync method on ComponentBase and RenderHandle. This allows you to handle these exceptions using Blazor’s error handling features (such as error boundaries).

Hot reload support< Instance fields, properties and events on strong>WebAssemblyon.NET

.NET on WebAssembly now supports adding instance fields, properties, and events to existing classes when using hot reloading. This also enables other C# and Razor language features that use instance fields under the hood, such as certain types of C# lambdas and certain uses of the Razor @bind directive.

onWebAssembly< strong>Support symbol server

when debugging on.NET

When debugging .NET on WebAssembly, the debugger will now download symbol data from the symbol location configured in Visual Studio preferences. This improves the debugging experience for apps that use NuGet packages.

Blazor in Firefox WebAssemblyDebugging

You can now debug Blazor WebAssembly applications using Firefox. Debugging a Blazor WebAssembly app requires configuring the browser for remote debugging, and then connecting to the browser using the browser developer tools through the .NET WebAssembly debug agent. Debuggin Firefox from Visual Studio is not currently supported.

To debug a Blazor WebAssembly app in Firefox during development:

  1. Open the Blazor WebAssembly application in Firefox.
  2. Open Firefox Web Developer Tools and go to the Console tab.
  3. With the Blazor WebAssembly app in focus, type the debug command SHIFT + ALT + D.
  4. Follow the instructions in the development console output to configure Firefox for Blazor WebAssembly debugging:
    • Open About: Configure in Firefox
    • Enable devtools.debugger.remote-enabled
    • Enable devtools.chrome.enabled
    • Disable devtools.debugger.prompt-connection
  5. Close all instances of Firefox, then reopen Firefox and enable remote debugging by running firefox –start-debugger-server 6000 -new-tab about:debugging.
  6. In the new Firefox instance, leave the about:debugging tab open, then open the Blazor WebAssembly app in a new browser tab.
  7. Type SHIFT + ALT to open the Firefox Web Developer tool and connect to the Firefox browser instance.
  8. In the “Debugger” tab of the Web developer tool, open the application source file to be debugged under the file:// node and set a breakpoint. For example, set a breakpoint in the IncrementCount method of Pages/Counter.razor.
  9. Navigate to the counters page and click the counter button to hit the breakpoint.

.NETExperimental assemblies< /strong>WebcilFormat

In some environments, firewalls and antivirus tools block the downloading or use of .dll files, thereby preventing the use of web applications based on .NET assemblies, such as Blazor WebAssembly applications. To address this issue, the wasm-experimental workload now supports a new .webcil file format that can be used to package .NET assemblies for browser-based web applications. Currently, the Webcil format is only available for experimental WebAssembly browser apps, but we plan to enable it for Blazor WebAssembly apps in a future update.

To try out the new Webcil format using the WebAssembly browser app:

  1. Install workload: wasm-experimentaldotnet workload install wasm-experimental
  2. Create a new application: dotnet new wasmbrowser
  3. Add properties to file: WasmEnableWebcil.csproj
<PropertyGroup>
    <WasmEnableWebcil>true</WasmEnableWebcil>
</PropertyGroup>

4. Run the app and verify in the browser that the .webcil file is being downloaded, not the .dll file.

If you encounter problems using .webcil files in your environment, please let us know by creating an issue on GitHub.

Specify the BlazorWebView to be loadedBlazorWebView< strong>InitialURL

The new property StartPath on BlazorWebView allows you to set the path to which you initially navigate. This is useful when you want to take the user directly to a specific page after the BlazorWebView loads.

KeepSPA New options for development server running

When using ASP.NET Core to build a single-page application (SPA), both the SPA development server and the back-end ASP.NET Core need to be executed during the development process. The SPA development server is configured to proxy API requests to the ASP.NET Core backend. When the ASP.NET Core process terminates, by default the SPA development server also terminates. Restarting the SPA development server can be time-consuming and tedious. The new KeepRunning option enabled by SpaDevelopmentServerOptions allows the SPA development server to remain running even if the ASP.NET Core process is terminated.

SupportKestrel Named Pipes

Named pipes are a popular technology used to build inter-process communication (IPC) between Windows applications. IPC servers can now be generated using .NET, Kestrel and Named Pipes.

var builder = WebApplication.CreateBuilder(args);
builder.WebHost.ConfigureKestrel(serverOptions =>
{
    serverOptions.ListenNamedPipe("MyPipeName");
});

For more information about this feature and how to create IPC servers and clients using .NET and gRPC, see Inter-Process Communication with gRPC.

Enabled by defaultHTTP/3

HTTP/3 is an exciting new technology for the Internet, standardized in March 2022. HTTP/3 offers several advantages over the older HTTP protocol, including:

  • Faster connection settings.
  • No head blocking.
  • Better conversion between networks.

.NET 7 adds support for HTTP/3 to ASP.NET Core and Kestrel. ASP.NET Core apps can choose to turn it on. In .NET 8, we enable HTTP/3 (along with HTTP/1.1 and HTTP/2) by default.

?

For more information about HTTP/3 and its requirements, see Using HTTP/3 with the ASP.NET Core Kestrel web server.

macOS strong>HTTP/2 over TLS (HTTPS) support

You can now use TLS and HTTP/2 with ASP.NET Core on macOS. .NET 8 adds support for Application Layer Protocol Negotiation (ALPN) to macOS. ALPN is a TLS feature used to negotiate the HTTP protocol that the connection will use. For example, ALPN allows browsers and other HTTP clients to request HTTP/2 connections. This feature is particularly useful for gRPC applications requiring HTTP/2.

Great to see this friction point gone on macOS!

gRPC JSONConversion Code no longer requiredhttp.protoandannotations.proto

gRPC JSON transcoding is an extension to ASP.NET Core that creates RESTful JSON APIs for gRPC services. Once configured, transcoding allows applications to call gRPC services using familiar HTTP concepts such as HTTP verbs, URL parameter bindings, and JSON requests/responses.

We’ve simplified the process of adding JSON transcoding to .NET gRPC applications. It is no longer necessary to copy the http.proto file and the annotations.proto file into the application. In .NET 8 Preview 1, these files are included in the NuGet package and automatically referenced for you.

Specify server timeout and use HubConnectionBuilder Keep-alive interval setting

You can now specify the server timeout and keep-alive interval settings for SignalR clients using a HubConnectionBuilder. This is useful in Blazor Server apps if you want to increase the timeout while debugging to avoid encountering timeouts when execution is paused.

Blazor.start({
    configureSignalR: function (builder) {
        builder
          .withServerTimeout(60000)
          .withKeepAliveInterval(30000);
    };
});

IPNetwork.Parseand TryParse

The new Parse and TryParse methods on IPNetwork add support for creating IPNetworks using input strings in CIDR notation or “slash notation”.

IPv4

// Using Parse
var network = IPNetwork.Parse("192.168.0.1/32");

// Using TryParse
bool success = IPNetwork.TryParse("192.168.0.1/32", out var network);

//Ctor equivalent
var network = new IPNetwork(IPAddress.Parse("192.168.0.1"), 32);

IPv6

// Using Parse
var network = IPNetwork.Parse("2001:db8:3c4d::1/128");

// Using TryParse
bool success = IPNetwork.TryParse("2001:db8:3c4d::1/128", out var network);

//Ctor equivalent
var network = new IPNetwork(IPAddress.Parse("2001:db8:3c4d::1"), 128);

Thanks to @david-acker for the contribution!

HTTP_PORTSandHTTPS_PORTSConfiguration support

Applications and containers are often given just a port to listen on (such as 80), without additional constraints such as host or path. HTTP_PORTS and HTTPS_PORTS are new configuration keys that allow specifying the listening ports for Kestrel and HttpSys servers. These can be defined using the DOTNET_ or ASPNETCORE_ environment variable prefix, or can be specified directly via any other configuration input (such as appsettings.json). Each port value is a semicolon-separated list of port values.

ASPNETCORE_HTTP_PORTS=80;8080
ASPNETCORE_HTTPS_PORTS=443;8081

This is shorthand for the following, which specifies the scheme (HTTP or HTTPS) and any host or IP.

ASPNETCORE_URLS=http://*:80/;http://*:8080/;https://*:443/;https://*:8081/

These new configuration keys have lower priority and will be overridden by URLs or values provided directly in code. Certificates still need to be configured individually via the server-specific HTTPS mechanism.

Not using the specified HTTP protocolHTTPWarning during agreement

If TLS is disabled and HTTP/1.x is available, HTTP/2 and HTTP/3 will be disabled, even if they are specified. This can lead to some nasty surprises, so we’ve added a warning output to notify you if it happens.

Provide feedback

We hope you enjoy the preview of ASP.NET Core in .NET 8. Let us know what you think of these new improvements by submitting an issue on GitHub.

Thanks for trying ASP.NET Core!

ASP.NET Core updates in .NET 8 Preview 1

syntaxbug.com © 2021 All Rights Reserved.