ASP.NET Core in .NET 8 is Coming! Discover its NEW Features🚀

bytehide

ByteHide

Posted on April 7, 2023

ASP.NET Core in .NET 8 is Coming! Discover its NEW Features🚀

ASP.NET Core has received updates in .NET 8 Preview 1, including Blazor United, improved route tooling, and HTTP/3 enabled by default. In this article, we will take a closer look at these features!

Route Tooling

Routing is a fundamental part of building web applications with ASP.NET Core. In .NET 8 Preview 1, the route tooling has received several new features and these features include:

  • Syntax highlighting for routes
  • Autocomplete for parameter and route names
  • Autocomplete for route constraints
  • Route analyzers and fixers

One of the most exciting things about the new route tooling is that it’s built on Roslyn, which means it automatically adapts to the IDE that you’re using.

This makes it incredibly easy to use, regardless of whether you prefer Visual Studio, VS Code, or another IDE.

a

source: devblogs.microsoft.com

The new route tooling supports Minimal APIs, Web APIs, and Blazor, which means you can use it to build a wide range of web applications.

The route tooling is designed to help you catch and fix common routing issues, and it’s available in all of the major IDEs that support ASP.NET Core development.

Route Constraint Performance Improvements

Routing is a powerful and high-performance technology used by almost all ASP.NET Core apps, and route constraints are a commonly used feature of routing that helps match requests to the right endpoint.

In .NET 8, several performance improvements have been made to constraints to maximize runtime performance and reduce startup time and memory use:



// 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) => { /* ... */ });


Enter fullscreen mode Exit fullscreen mode

In this example, a regex constraint is used to ensure that the “name” parameter matches a specific pattern.

In .NET 8, several performance improvements have been made to constraints:

  • Regex constraints are now compiled, which improves runtime performance. Compiled regexes have a one-time cost at startup, but subsequent matches are faster.
  • Duplicate constraints are now shared between routes, which reduces startup time and memory use. If multiple routes use the same constraint, it only needs to be compiled once and can be shared across all the routes.
  • The alpha constraint now uses a source generated regex, which improves performance. This constraint matches any alphabetic character and uses a source-generated regular expression.

New Analyzers for API Development

In .NET 8, Microsoft has introduced a suite of new analyzers that provide warnings and recommendations to improve the quality of ASP.NET Core APIs.

One of the new analyzers recommends setting or appending to a HeaderDictionary instead of using the IHeaderDictionary.Add API, which can throw an exception if duplicate keys are added.

Instead, developers can leverage the indexer or the IHeaderDictionary.Append API to set, override, or append to a header. Here’s an example of using IHeaderDictionary.Append:



var context = new DefaultHttpContext();
context.Request.Headers.Append("Accept", "text/html"); // No warning issued


Enter fullscreen mode Exit fullscreen mode

Another analyzer warns if a parameter type passed to a route handler does not implement the correct interfaces.

For example, the Customer type in the code below will trigger a warning because it does not implement a BindAsync method with the correct signature:



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

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


Enter fullscreen mode Exit fullscreen mode

This warning helps developers ensure that their APIs are robust and that the appropriate interfaces are implemented for proper operation.

Finally, the RequestDelegate analyzer detects if a RequestDelegate is implemented incorrectly.

This analyzer ensures that the response of the RequestDelegate is not discarded at runtime and recommends the use of c.Response.WriteAsync or minimal APIs instead. Here’s an example of using c.Response.WriteAsync:



var app = WebApplication.Create();
Task HelloWorld(HttpContext c) => c.Response.WriteAsync("Hello World!"); // No warning issued 
app.MapGet("/", HelloWorld); 


Enter fullscreen mode Exit fullscreen mode

These new analyzers are a valuable addition to the ASP.NET Core development experience, helping developers create high-quality code that is easier to debug, test, and maintain.

Blazor WebAssembly Debugging in Firefox

Debugging Blazor WebAssembly apps is now possible using Firefox, thanks to the latest updates in .NET 8 Preview 1.

Debugging Blazor WebAssembly apps requires configuring the browser for remote debugging and then connecting to the browser using the browser developer tools through the .NET WebAssembly debugging proxy. At this time, debugging Firefox from Visual Studio is not supported.

To debug a Blazor WebAssembly app in Firefox during development, follow these steps.

a

source: devblogs.microsoft.com

This is a valuable addition to the Blazor WebAssembly development experience and helps developers debug their apps more easily.

Experimental Webcil format for .NET assemblies

In some environments, firewalls and anti-virus tools block the download or use of .dll files, which prevents the use of web apps based on .NET assemblies, like Blazor WebAssembly apps.

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 apps.

To try out the new Webcil format with a WebAssembly Browser App, follow these steps:

  • Install the wasm-experimental workload: dotnet workload install wasm-experimental
  • Create a new app: dotnet new wasmbrowser
  • Add the WasmEnableWebcil property to the .csproj file


<PropertyGroup>
<WasmEnableWebcil>true</WasmEnableWebcil></PropertyGroup>


Enter fullscreen mode Exit fullscreen mode
  • Run the app and verify in the browser’s DevTools that .webcil files are being downloaded, not .dll files.

The Webcil format is currently only available for the experimental WebAssembly Browser Apps, but Microsoft plans to enable it for Blazor WebAssembly apps in a future update.

Specify initial URL for BlazorWebView to load

The new StartPath property on BlazorWebView allows you to set the path to initially navigate to. This is useful when you want to take the user straight to a specific page once the BlazorWebView is loaded.



<BlazorWebView StartPath="/counter" HostPage="index.html" />


Enter fullscreen mode Exit fullscreen mode

New option to keep the SPA development server running

When building a single-page app (SPA) with ASP.NET Core, both the SPA development server and the backend ASP.NET Core need to execute during development.

The SPA development server is configured to proxy API requests to the ASP.NET Core backend.

The new KeepRunning option on SpaDevelopmentServerOptions enables leaving the SPA development server running even if the ASP.NET Core process is terminated.



var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSpaStaticFiles(configuration =>
{
    configuration.RootPath = "ClientApp/build";
});
builder.Services.AddControllers();
builder.Services.AddSpa(options =>
{
    options.SourcePath = "ClientApp";
    options.UseReactDevelopmentServer(npmScript: "start");
    options.Options.SourcePath = "ClientApp";
    options.Options.StartupTimeout = TimeSpan.FromSeconds(120);
    options.Options.KeepRunning = true; // Enables the new option
});


Enter fullscreen mode Exit fullscreen mode

Support for named pipes in Kestrel

Named pipes is a popular technology for building inter-process communication (IPC) between Windows apps. You can now build an IPC server using .NET, Kestrel, and named pipes.



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


Enter fullscreen mode Exit fullscreen mode

For more information about this feature and how to use .NET and gRPC to create an IPC server and client, see Inter-process communication with gRPC.

HTTP/3 enabled by default

HTTP/3 is a new internet technology that offers several advantages over older HTTP protocols, including faster connection setup, no head-of-line blocking, and better transitions between networks.

In .NET 7, support for HTTP/3 was added to ASP.NET Core and Kestrel, but in .NET 8, it is enabled by default alongside HTTP/1.1 and HTTP/2.

a

source: devblogs.microsoft.com

Some key points about HTTP/3 in .NET 8:

  • Enabled by default in ASP.NET Core and Kestrel.
  • Faster connection setup and no head-of-line blocking.
  • Better transitions between networks.
  • Supports HTTP/1.1 and HTTP/2.
  • Enables clients to use QUIC instead of TCP for transport.

To enable HTTP/3 in a .NET 8 project, you can use the following code in your ASP.NET Core app:



WebHost.CreateDefaultBuilder(args)
       .UseKestrel(options =>
       {
           options.Listen(IPAddress.Any, 5001, listenOptions =>
           {
               listenOptions.Protocols = HttpProtocols.Http3;
           });
       })
       .UseStartup<Startup>();     .UseStartup<Startup>();


Enter fullscreen mode Exit fullscreen mode

In the above example, we are using the UseKestrel method to configure Kestrel as the web server and Listen to specify the IP address and port to listen on. The HttpProtocols.Http3 option is used to enable HTTP/3.

đź’– đź’Ş đź™… đźš©
bytehide
ByteHide

Posted on April 7, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related