April 8th, 2021

ASP.NET Core updates in .NET 6 Preview 3

Daniel Roth
Principal Product Manager

.NET 6 Preview 3 is now available and includes many great new improvements to ASP.NET Core.

Here’s what’s new in this preview release:

  • Smaller SignalR, Blazor Server, and MessagePack scripts
  • Enable Redis profiling sessions
  • HTTP/3 endpoint TLS configuration
  • Initial .NET Hot Reload support
  • Razor compiler no longer produces a separate Views assembly
  • Shadow-copying in IIS
  • Vcpkg port for SignalR C++ client
  • Reduced memory footprint for idle TLS connections
  • Remove slabs from the SlabMemoryPool
  • BlazorWebView controls for WPF & Windows Forms

Get started

To get started with ASP.NET Core in .NET 6 Preview 3, install the .NET 6 SDK.

If you’re on Windows using Visual Studio, we recommend installing the latest preview of Visual Studio 2019 16.10. If you’re on macOS, we recommend installing the latest preview of Visual Studio 2019 for Mac 8.10.

Upgrade an existing project

To upgrade an existing ASP.NET Core app from .NET 6 Preview 2 to .NET 6 Preview 3:

  • Update all Microsoft.AspNetCore.* package references to 6.0.0-preview.3.*.
  • Update all Microsoft.Extensions.* package references to 6.0.0-preview.3.*.
  • Update calls to TryRedeemPersistedState on ComponentApplicationState to call TryTakePersistedState instead.
  • Update calls to TryRedeemFromJson on ComponentApplicationState to call TryTakeAsJson instead.

See the full list of breaking changes in ASP.NET Core for .NET 6.

Smaller SignalR, Blazor Server, and MessagePack scripts

Thanks to a community contribution from Ben Adams the SignalR, MessagePack, and Blazor Server scripts are now significantly smaller, enabling smaller downloads, less JavaScript parsing and compiling by the browser, and faster start-up.

The download size reduction from this work is pretty phenomenal:

Library Before After % 🠓 .br
signalr.min.js 130 KB 39 KB 70% 10 KB
blazor.server.js 212 KB 116 KB 45% 28 KB

You also now only need the @microsoft/signalr-protocol-msgpack package for MessagePack; no need to include msgpack5. This means you only need an additional 29 KB rather than the earlier 140 KB to use MessagePack instead of JSON.

Here’s how this size reduction was achieved:

  • Updated TypeScript and dependencies to latest versions.
  • Switched from uglify-js to terser, which is webpack’s default and supports newer JavaScript language features (like class).
  • Marked the SignalR modules as "sideEffects": false so tree-shaking is more effective.
  • Dropped the "es6-promise/dist/es6-promise.auto.js" polyfill.
  • Changed TypeScript to output es2019 rather than es5 and dropped the “es2015.promise” and “es2015.iterable” polyfills.
  • Moved to msgpack5 from @msgpack/msgpack as it requires less polyfills and is TypeScript & module aware.

You can find more details on these changes in Ben’s pull request on GitHub.

Enable Redis profiling sessions

We accepted a community contribution from Gabriel Lucaci to enable Redis profiling session with Microsoft.Extensions.Caching.StackExchangeRedis in this preview. For more details on Redis profiling, see the official documentation. The API can be used as follows:

services.AddStackExchangeRedisCache(options =>
{
    options.ProfilingSession = () => new ProfilingSession();
})

HTTP/3 endpoint TLS configuration

Work is beginning to ramp up on support for HTTP/3 in .NET 6. HTTP/3 brings a number of advantages over existing HTTP protocols, including faster connection setup, and improved performance on low-quality networks.

New in this preview is the ability to configure TLS certificates on individual HTTP/3 ports with UseHttps. This brings Kestrel’s HTTP/3 endpoint configuration in-line with HTTP/1.1 and HTTP/2.

.ConfigureKestrel((context, options) =>
{
    options.EnableAltSvc = true;
    options.Listen(IPAddress.Any, 5001, listenOptions =>
    {
        listenOptions.Protocols = HttpProtocols.Http3;
        listenOptions.UseHttps(httpsOptions =>
        {
            httpsOptions.ServerCertificate = LoadCertificate();
        });
    });
})

Initial .NET Hot Reload support

Early support for .NET Hot Reload is now available for ASP.NET Core & Blazor projects using dotnet watch. .NET Hot Reload applies code changes to your running app without restarting it and without losing app state.

To try out hot reload with an existing ASP.NET Core project based on .NET 6, add the "hotReloadProfile": "aspnetcore" property to your launch profile in launchSettings.json. For Blazor WebAssembly projects, use the "blazorwasm" hot reload profile.

Run the project using dotnet watch. The output should indicate that hot reload is enabled:

watch : Hot reload enabled. For a list of supported edits, see https://aka.ms/dotnet/hot-reload. Press "Ctrl + R" to restart.

If at any point you want to force the app to rebuild and restart, you can do so by entering Ctrl+R at the console.

You can now start making edits to your code. As you save code changes, applicable changes are automatically hot reloaded into the running app almost instantaneously. Any app state in the running app is preserved.

.NET Hot Reload

You can hot reload changes to your CSS files too without needing to refresh the browser:

CSS hot reload

Some code changes aren’t supported with .NET Hot Reload. You can find a list of supported code edits in the docs. With Blazor WebAssembly only method body replacement is currently supported. We’re working to expand the set of supported edits in .NET 6. When dotnet watch detects a change that cannot be applied using hot reload, it falls back to rebuilding and restarting the app.

This is just the beginning of hot reload support in .NET 6. Hot reload support for desktop and mobile apps will be available soon in an upcoming preview as well as integration of hot reload in Visual Studio.

Razor compiler no longer produces a separate Views assembly

The Razor compiler previously utilized a two-step compilation process that produced a separate Views assembly that contained the generated views and pages (.cshtml) defined in the application. The generated types were public and under the AspNetCore namespace.

We’ve now updated the Razor compiler to build the views and pages types into the main project assembly. These types are now generated by default as internal sealed in the AspNetCoreGeneratedDocument namespace. This change improves build performance, enables single file deployment, and enables these types to participate in .NET Hot Reload.

For additional details about this change, see the related announcement issue on GitHub.

Shadow-copying in IIS

We’ve added a new feature in the ASP.NET Core Module for IIS to add support for shadow-copying your application assemblies. Currently .NET locks application binaries when running on Windows making it impossible to replace binaries when the application is still running. While our recommendation remains to use an app offline file, we recognize there are certain scenarios (for example FTP deployments) where it isn’t possible to do so.

In such scenarios, you can enable shadow copying by customizing the ASP.NET Core module handler settings. In most cases, ASP.NET Core application do not have a web.config checked into source control that you can modify (they are ordinarily generated by the SDK). You can add this sample web.config to get started.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <!-- To customize the asp.net core module uncomment and edit the following section. 
  For more info see https://go.microsoft.com/fwlink/?linkid=838655 -->

  <system.webServer>
    <handlers>
      <remove name="aspNetCore"/>
      <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModulev2" resourceType="Unspecified"/>
    </handlers>
    <aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout">
      <handlerSettings>
        <handlerSetting name="experimentalEnableShadowCopy" value="true" />
        <handlerSetting name="shadowCopyDirectory" value="../ShadowCopyDirectory/" />
        <!-- Only enable handler logging if you encounter issues-->
        <!--<handlerSetting name="debugFile" value=".\logs\aspnetcore-debug.log" />-->
        <!--<handlerSetting name="debugLevel" value="FILE,TRACE" />-->
      </handlerSettings>
    </aspNetCore>
  </system.webServer>
</configuration>

You require a new version of ASP.NET Core module to try to this feature. On a self-hosted IIS server, this requires a new version of the hosting bundle. On Azure App Services, you will be required to install a new ASP.NET Core runtime site extension

ASP.NET Core runtime site extension

Vcpkg port for SignalR C++ client

Vcpkg is a cross-platform command-line package manager for C and C++ libraries. We’ve recently added a port to vcpkg to add CMake native support (works with MSBuild projects as well) for the SignalR C++ client.

You can add the SignalR client to your CMake project with the following snippet (assuming you’ve already included the vcpkg toolchain file):

find_package(microsoft-signalr CONFIG REQUIRED)
link_libraries(microsoft-signalr::microsoft-signalr)

After this, the SignalR C++ client is ready to be #include’d and used in your project without any additional configuration. For a complete example of a C++ application that utilizes the SignalR C++ client, check out this repository.

Reduced memory footprint for idle TLS connections

For long running TLS connections where data is only occasionally sent back and forth, we’ve significantly reduced the memory footprint of ASP.NET Core apps in .NET 6. This should help improve the scalability of scenarios such as WebSocket servers. This was possible due to numerous improvements in System.IO.Pipelines, SslStream and Kestrel. Let’s look at some of the improvements that have contributed to this scenario:

Reduce the size of System.IO.Pipelines.Pipe

For every connection that we establish, we allocate two pipes in Kestrel: one from the transport layer to the application for the request and another from the application layer to the transport for the response. By shrinking the size of System.IO.Pipelines.Pipe from 368 bytes to 264 bytes (~28.2%), we’re saving 208 bytes per connection (104 bytes per Pipe).

Pool SocketSender

SocketSender objects (that subclass SocketAsyncEventArgs) are around 350 bytes at runtime. Instead of allocating a new SocketSender object per connection, we can pool them since sends are usually very fast and we can reduce the per connection overhead. Instead of paying 350 bytes per connection, we now only pay 350 bytes per IOQueue(one per queue to avoid contention). In our WebSocket server with 5000 idle connections we went from allocating ~1.75 MB (350 bytes * 5000) to now allocating just ~2.8kb (350 bytes * 8) for SocketSender objects.

Zero bytes reads with SslStream

Bufferless reads are a technique we already employ in ASP.NET Core to avoid renting memory from the memory pool if there’s no data available on the socket. Prior to this change, our WebSocket server with 5000 idle connections required ~200 MB without TLS compared to ~800 MB with TLS. Some of these allocations (4k per connection) were from Kestrel having to hold on to an ArrayPool buffer while waiting for the reads on SslStream to complete. Given that these connections were idle, none of reads completed and return their buffers to the ArrayPool forcing the ArrayPool to allocate more memory. The remaining allocations were in SslStream itself: 4k buffer for TLS handshakes and 32k buffer for normal reads. In preview3, when the user performs a zero byte read on SslStream and it has no data available, SslStream will internally perform a zero-byte read on the underlying wrapped stream. In the best case (idle connection), these changes result in a savings of 40 Kb per connection while still allowing the consumer (Kestrel) to be notified when data is available without holding on to any unused buffers.

Zero byte reads with PipeReader

Once SslStream supported bufferless reads, we then added the option to perform zero byte reads to StreamPipeReader, the internal type that adapts a Stream into a PipeReader. In Kestrel, we use a StreamPipeReader to adapt the underlying SslStream into a PipeReader and it was necessary to expose these zero byte read semantics on the PipeReader.

You can now create a PipeReader that supports zero bytes reads over any underlying Stream that supports zero byte read semantics (e.g,. SslStream, NetworkStream, etc) using the following API:

var reader = PipeReader.Create(stream, new StreamPipeReaderOptions(useZeroByteReads: true));

Remove slabs from the SlabMemoryPool

To reduce fragmentation of the heap, Kestrel employed a technique where it allocated slabs of memory of 128 KB as part of it’s memory pool. The slabs were then further divided into 4 KB blocks that were used by Kestrel internally. The slabs had to be larger than 85 KB to force allocation on the large object heap to try and prevent the GC from relocating this array. However, with the introduction of the new GC generation, Pinned Object Heap (POH), it no longer makes sense to allocate blocks on slab. In preview3, we now directly allocate blocks on the POH, reducing the complexity involved in managing our own memory pool. This change should make easier to perform future improvements such as making it easier to shrink the memory pool used by Kestrel.

BlazorWebView controls for WPF & Windows Forms

For .NET 6 we are adding support for building cross-platform hybrid desktop apps using .NET MAUI and Blazor. Hybrid apps are native apps that leverage web technologies for their functionality. For example, a hybrid app might use an embedded web view control to render web UI. This means you can write your app UI using web technologies like HTML & CSS, while also leveraging native device capabilities. We will be introducing support for building hybrid apps with .NET MAUI and Blazor in an upcoming .NET 6 preview release.

In this release, we’ve introduced BlazorWebView controls for WPF and Windows Forms apps that enable embedding Blazor functionality into existing Windows desktop apps based on .NET 6. Using Blazor and a hybrid approach you can start decoupling your UI investments from WPF & Windows Forms. This is a great way to modernize existing desktop apps in a way that can be brought forward onto .NET MAUI or used on the web. You can use Blazor to modernize your existing Windows Forms and WPF apps while leveraging your existing .NET investments.

To use the new BlazorWebView controls, you first need to make sure that you have WebView2 installed.

To add Blazor functionality to an existing Windows Forms app:

  • Update the Windows Forms app to target .NET 6.
  • Update the SDK used in the app’s project file to Microsoft.NET.Sdk.Razor.
  • Add a package reference to Microsoft.AspNetCore.Components.WebView.WindowsForms.
  • Add the following wwwroot/index.html file to the project, replacing {PROJECT NAME} with the actual project name:
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <title>Blazor app</title>
    <base href="/" />
    <link href="{PROJECT NAME}.styles.css" rel="stylesheet" />
    <link href="app.css" rel="stylesheet" />
</head>

<body>
    <div id="app"></div>

    <div id="blazor-error-ui">
        An unhandled error has occurred.
        <a href="" class="reload">Reload</a>
        <a class="dismiss">🗙</a>
    </div>

    <script src="_framework/blazor.webview.js"></script>
</body>
</html>
  • Add the following app.css file with some basic styles to the wwwroot folder:
html, body {
    font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
}

.valid.modified:not([type=checkbox]) {
    outline: 1px solid #26b050;
}

.invalid {
    outline: 1px solid red;
}

.validation-message {
    color: red;
}

#blazor-error-ui {
    background: lightyellow;
    bottom: 0;
    box-shadow: 0 -1px 2px rgba(0, 0, 0, 0.2);
    display: none;
    left: 0;
    padding: 0.6rem 1.25rem 0.7rem 1.25rem;
    position: fixed;
    width: 100%;
    z-index: 1000;
}

    #blazor-error-ui .dismiss {
        cursor: pointer;
        position: absolute;
        right: 0.75rem;
        top: 0.5rem;
    }
  • For all files in the wwwroot folder, set the Copy to Output Directory property to Copy if newer.
  • Add a root Blazor component, Counter.razor, to the project:
@using Microsoft.AspNetCore.Components.Web

<h1>Counter</h1>

<p>The current count is: @currentCount</p>
<button @onclick="IncrementCount">Count</button>

@code {
    int currentCount = 0;

    void IncrementCount()
    {
        currentCount++;
    }
}
  • Add a BlazorWebView control to the desired form to render the root Blazor component:
var serviceCollection = new ServiceCollection();
serviceCollection.AddBlazorWebView();
var blazor = new BlazorWebView()
{
    Dock = DockStyle.Fill,
    HostPage = "wwwroot/index.html",
    Services = serviceCollection.BuildServiceProvider(),
};
blazor.RootComponents.Add<Counter>("#app");
Controls.Add(blazor);
  • Run the app to see your BlazorWebView in action:

Blazor Windows Forms

To add Blazor functionality to an existing WPF app, follow the same steps listed above for Windows Forms apps, except:

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        xmlns:blazor="clr-namespace:Microsoft.AspNetCore.Components.WebView.Wpf;assembly=Microsoft.AspNetCore.Components.WebView.Wpf"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <blazor:BlazorWebView HostPage="wwwroot/index.html" Services="{StaticResource services}">
            <blazor:BlazorWebView.RootComponents>
                <blazor:RootComponent Selector="#app" ComponentType="{x:Type local:Counter}" />
            </blazor:BlazorWebView.RootComponents>
        </blazor:BlazorWebView>
    </Grid>
</Window>
  • Set up the service provider as a static resource in the XAML code-behind file (such as MainWindow.xaml.cs):
var serviceCollection = new ServiceCollection();
serviceCollection.AddBlazorWebView();
Resources.Add("services", serviceCollection.BuildServiceProvider());
  • To workaround an issue with the WPF runtime build not finding Razor component types, add an empty partial class for the component in Counter.razor.cs:
public partial class Counter { }
  • Build and run your Blazor based WPF app:

Blazor WPF

Give feedback

We hope you enjoy this preview release of ASP.NET Core in .NET 6. We’re eager to hear about your experiences with this release. Let us know what you think by filing issues on GitHub.

Thanks for trying out ASP.NET Core!

Author

Daniel Roth
Principal Product Manager

Daniel Roth is a Program Manager on the ASP.NET team at Microsoft.

75 comments

Discussion is closed. Login to edit/delete existing comments.

  • Ric W

    Hi Daniel,
    I've recently been playing with BlazorWebView

    One quick question, is it possible to extract the raw html from BlazorWebView as a string?
    (this is for the purposes of feeding into iText7 / pdfHTML to generate a pdf report)

    So far I've managed to get MudBlazor working with it under WinForms (which looks a lot better than the native WinForms controls and I think allows for all the UI goodness from javascript land such as Babylon...

    Read more
  • Roy Cristian Zegarra Aguirre · Edited

    Hello Daniel, since I met Blazor I have become a fan so I congratulate you for your great work, however I see it necessary to improve the reconnection when it falls for some reason. I understand that being connected through SignalR this connection is persistent and any network drop for more than a few seconds the connection is lost and in some cases it cannot be reconnected so the user must reload the page and...

    Read more
    • Daniel RothMicrosoft employee Author

      Hi Roy. Thanks for this feedback! We do support reconnection in Blazor Server. If the connection is dropped we will hold on to the circuit state for a while to allow the client to reconnect. However, Blazor won't hold on to the disconnected circuit indefinitely, and if the circuit state on the server is lost for any reason, like due to a server restart or reconnection timeout, then the client will need to refresh the...

      Read more
  • 添昊 栾

    Another question, what is the 3D solution for .net6? except unity, we need kind of three.js\Qt Quick 3D\QT 3D something to draw 3d models in our app.

  • 添昊 栾

    I see MAUI is for android, ios, mac and windows, but can MAUI for the web? just like flutter? or we can only use blazor for the web?I hate html and css…but without MAUI for web, it’s useless for us.

    • Daniel RothMicrosoft employee Author

      Bringing .NET MAUI to the web is certainly a possibility. .NET MAUI is designed to be able to run on any platform, and the web is just another platform. But it's not planned for .NET 6.

      If working on brining .NET MAUI to the web is something you're company is interested in, I would suggest reaching out to the .NET MAUI folks on GitHub: https://github.com/dotnet/maui/discussions/62.

      There's also a related community effort called Ooui that's worth a look:...

      Read more
      • 添昊 栾

        Thank you for reply, so in .net6, Blazor is really cross-platform: android, ios, windows, mac, browser, server, and MAUI is only for android, ios, windows, mac, right? what's the difference between a maui app and a blazor Hybrid app except ui skill? does blazor native app has the native performance?
        If yes, we can consider start blazor for new project now, despite we don't like css and html, but it's the only option if we...

        Read more
      • Daniel RothMicrosoft employee Author

        Blazor is a web UI framework, so it benefits from the cross-platform nature of the web. All you need is a web browser to run a Blazor web app. But web apps run in a security sandbox and only have limited access to the native capabilities of the device.

        .NET MAUI apps are cross-platform native apps. A .NET MAUI app runs natively on the device and renders native UI elements from the underlying platform.

        By hosting Blazor...

        Read more
  • Aleksander Kovač · Edited

    Hi .NET team, the work you are doing is really awesome. Even in this preview version, the hot reload feature works really well for Blazor. The general impression is very high productivity for enterprise apps. Sure there is an occasional issue, we’ll report the details if we recognize a pattern.

    To summarize, we are very optimistic about using .NET for our enterprise projects.

  • Luis Harvey Triana Vega

    When we go to install ML.NET in Blazor WebAssembly application, this issue still persists: "The RuntimeIdentifier platform 'browser-wasm' and the PlatformTarget 'x64' must be compatible".

    OK, maybe it should be normal not to be able to run machine learning on the client, however, we should be able to instantiate the prediction engine. The ML.NET development team, or Blazor (maybe for final net6 version), should consider publishing a simplified module taking only that part of ML.NET that...

    Read more
  • Lucian Parvu · Edited

    Hi,

    I have a project Blazor Server with ~ 180 .razor Files (186 Files, 55 Folder)

    If all folder structure is in the same project the hot reload takes ~ 15 seconds , more than build time ( 10 seconds ) .

    If we split the .razor files on Libraries , we get the next Results

    Main App (Only Host.razor) : (Reference to Shared Library, Front Library,Admin Library )
    - Hot Reload for all tests after 1 seconds

    Shared...

    Read more
    • Daniel RothMicrosoft employee Author

      Hi Lucian. Thank you for sharing this feedback! Hot reload in general should be very fast, often sub-second, so the behavior you are seeing is surprising. Could you please open a GitHub issue with this feedback so that we can investigate?

  • Dustyn Lightfoot

    Hi @Daniel,

    Thanks … loving your work!

    In the Hybrid Blazor MAUI (BlazorWebView) scenario – will it be possible to deploy the web aspects to a web server and pull it down at runtime, so that UI changes can be deployed without re-deploying the native MAUI app to the app stores?

    • Daniel RothMicrosoft employee Author · Edited

      No, the purpose of the BlazorWebVew is to enable rendering from components that are deployed with the app.

      • Dustyn Lightfoot

        Ah ok, thanks … good to know I didn’t waist a lot of time writing JS interop code 🙂

  • Patrick Szalapski · Edited

    OK, I'll be the first lame commenter that can't get Hot Reload to work.

    I got .NET 6 Preview 3 SDK, created a new Blazor Web Assembly PWA project using the default template via Visual Studio 16.10, and added to both the Server and Client launchSettings.json (is it supposed to be in both?). I ran and held my breath for this awesome new feature. Sadly, I never saw the expected as...

    Read more
  • Darrell Tunnell · Edited

    I'll be "that guy" then :-). Whats the story for rendering a blazor web view on linux too? WPF and Windows Forms are great windows only vehicles. I use wasm because of its amazing portability and ability to run anywhere. Blazor wasm lets me use c# to create wasm apps. If I could release my blazor wasm application in a vehicle that runs natively on any platform (which includes linux) then this would be worth...

    Read more
    • Daniel RothMicrosoft employee Author

      Hi Darrell. We are also building a BlazorWebView for .NET MAUI to support cross-platform scenarios. Initially .NET MAUI will support Windows, macOS, Android, and iOS, but once it supports Linux it will support Blazor on Linux too. Note that your Blazor components don't run on WebAssembly when you use a BlazorWebView. Instead your components run natively on the device and then communicate with the browser control using a local interop channel to handle rendering and...

      Read more