![]() |
|
ASP.NET Core updates in .NET 5 Release Candidate 1 - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: C#, Visual Basic & .NET (https://sickgaming.net/forum-79.html) +--- Thread: ASP.NET Core updates in .NET 5 Release Candidate 1 (/thread-97281.html) |
ASP.NET Core updates in .NET 5 Release Candidate 1 - xSicKxBot - 09-16-2020 ASP.NET Core updates in .NET 5 Release Candidate 1 Daniel September 14th, 2020 .NET 5 Release Candidate 1 (RC1) is now available and is ready for evaluation. Here’s what’s new in this release:
See the .NET 5 release notes for additional details and known issues. Get started To get started with ASP.NET Core in .NET 5 RC1 install the .NET 5 SDK. .NET RC1 also is included with Visual Studio 2019 16.8 Preview 3. You need to use Visual Studio 2019 16.8 Preview 3 or newer to use .NET 5 RC1. .NET 5 is also supported with the latest preview of Visual Studio for Mac. To use .NET 5 with Visual Studio Code, install the latest version of the C# extension. Upgrade an existing project To upgrade an existing ASP.NET Core app from .NET 5 Preview 8 to .NET 5 RC1:
In Blazor WebAssembly projects, also make the follwowing updates to the project file:
That’s it! You should be all ready to go. See also the full list of breaking changes in ASP.NET Core for .NET 5. What’s new? Blazor WebAssembly performance improvements For .NET 5, we’ve made significant improvements to Blazor WebAssembly runtime performance, with a specific focus on complex UI rendering and JSON serialization. In our performance tests, Blazor WebAssembly in .NET 5 is 2-3x faster for most scenarios. Runtime code execution in Blazor WebAssembly in .NET 5 is generally faster than Blazor WebAssembly 3.2 due to optimizations in the core framework libraries and improvements to the .NET IL interpreter. Things like string comparisons, dictionary lookups, and JSON handling are generally much faster in .NET 5 on WebAssembly. As shown in the chart below, JSON handling is almost twice as fast in .NET 5 on WebAssembly: We also optimized the performance of Blazor component rendering, particularly for UI involving lots of components, like when using high-density grids. To test the performance of grid component rendering in .NET 5, we used three different grid component implementations, each rendering 200 rows with 20 columns:
From our tests, grid rendering is 2-3x faster in .NET 5: You can find the code for these performance tests in the ASP.NET Core GitHub repo. You can expect ongoing work to improve Blazor WebAssembly performance. Besides optimizing the Blazor WebAssembly runtime and framework, the .NET team is also working with browser implementers to further speed up WebAssembly execution. And for .NET 6, we expect to ship support for ahead-of-time (AoT) compilation to WebAssembly, which should further improve performance. Blazor component virtualization You can further improve the perceived performance of component rendering using the new built-in virtualization support. Virtualization is a technique for limiting the UI rendering to just the parts that are currently visible, like when you have a long list or table with many rows and only a small subset is visible at any given time. Blazor in .NET 5 adds a new Code: VirtualizeA typical list or table-based component might use a C# foreach loop to render each item in the list or each row in the table, like this: Code: @foreach (var employee in employees)
{ <tr> <td>@employee.FirstName</td> <td>@employee.LastName</td> <td>@employee.JobTitle</td> </tr>
}If the list grew to include thousands of rows, then rendering it may take a while, resulting in a noticeable UI lag. Instead, you can replace the foreach loop with the Code: VirtualizeCode: <Virtualize Items="employees" Context="employee"> <tr> <td>@employee.FirstName</td> <td>@employee.LastName</td> <td>@employee.JobTitle</td> </tr>
</Virtualize>The Code: VirtualizeIf you don’t want to load all items into memory, you can specify an Code: ItemsProviderCode: <Virtualize ItemsProvider="LoadEmployees" Context="employee"> <tr> <td>@employee.FirstName</td> <td>@employee.LastName</td> <td>@employee.JobTitle</td> </tr>
</Virtualize>An items provider is a delegate method that asynchronously retrieves the requested items on demand. The items provider receives an Code: ItemsProviderRequestCode: ItemsProviderResult<TItem>Code: async ValueTask<ItemsProviderResult<Employee>> LoadEmployees(ItemsProviderRequest request)
{ var numEmployees = Math.Min(request.Count, totalEmployees - request.StartIndex); var employees = await EmployeesService.GetEmployeesAsync(request.StartIndex, numEmployees, request.CancellationToken); return new ItemsProviderResult<Employee>(employees, totalEmployees);
}Because requesting items from a remote data source might take some time, you also have the option to render a placeholder until the item data is available. Code: <Virtualize ItemsProvider="LoadEmployees" Context="employee"> <ItemContent> <tr> <td>@employee.FirstName</td> <td>@employee.LastName</td> <td>@employee.JobTitle</td> </tr> </ItemContent> <Placeholder> <tr> <td>Loading...</td> </tr> </Placeholder>
</Virtualize>The component tag helper now supports two additional render modes for prerendering a component from a Blazor WebAssembly app:
To setup prerendering in an Blazor WebAssembly app:
You can also pass parameters to the component tag helper when using the WebAssembly-based render modes if the parameters are serializable. The parameters must be serializable so that they can be transferred to the client and used to initialize the component in the browser. If prerendering, you’ll also need to be sure to author your components so that they can gracefully execute server-side without access to the browser. Code: <component type="typeof(Counter)" render-mode="WebAssemblyPrerendered" param-IncrementAmount="10" />In additional to improving the perceived load time of a Blazor WebAssembly app, you can also use the component tag helper with the new render modes to add multiple components on different pages and views. You don’t need to configure these components as root components in the app or add your own marker tags on the page – the framework handles that for you. Browser compatibility analyzer for Blazor WebAssembly Blazor WebAssembly apps in .NET 5 target the full .NET 5 API surface area, but not all .NET 5 APIs are supported on WebAssembly due to browser sandbox constraints. Unsupported APIs throw Code: PlatformNotSupportedExceptionWe haven’t added all of the annotations yet to the core libraries in .NET 5 to indicate which APIs are not supported in browsers, but some APIs, mostly Windows specific APIs, are already annotated: To enable browser compatibilty checks for libraries, add “browser” as a supported platform in your project file (Blazor WebAssembly projects and Razor class library projects do this for you): Code: <SupportedPlatform Include="browser" />When authoring a library, you can optionally indicate that a particular API is not supported in browsers by applying the Code: UnsupportedOSPlatformAttributeCode: [UnsupportedOSPlatform("browser")]
private static string GetLoggingDirectory()
{ // ...
}Blazor now enables you to isolate your JavaScript as standard JavaScript modules. This has a couple of benefits:
For example, the following JavaScript module exports a simple JavaScript function for showing a browser prompt: Code: export function showPrompt(message) { return prompt(message, 'Type anything here');
}You can add this JavaScript module to your .NET library as a static web asset (wwwroot/exampleJsInterop.js) and then import the module into your .NET code using the Code: IJSRuntimeCode: var module = await jsRuntime.InvokeAsync<JSObjectReference>("import", "./_content/MyComponents/exampleJsInterop.js");The “import” identifier is a special identifier used specifically for importing a JavaScript module. You specify the module using its stable static web asset path: _content/[LIBRARY NAME]/[PATH UNDER WWWROOT]. The Code: IJSRuntimeCode: JSObjectReferenceCode: JSObjectReferenceCode: public async ValueTask<string> Prompt(string message)
{ return await module.InvokeAsync<string>("showPrompt", message);
}Code: JSObjectReferenceBlazor file input support Blazor now offers an Code: InputFileThe Code: InputFileCode: InputFileCode: OnChangeCode: InputFileChangeEventArgsCode: <InputFile OnChange="OnInputFileChange" multiple /> <div class="image-list"> @foreach (var imageDataUrl in imageDataUrls) { <img src="@imageDataUrl" /> }
</div> @code { IList<string> imageDataUrls = new List<string>(); async Task OnInputFileChange(InputFileChangeEventArgs e) { var imageFiles = e.GetMultipleFiles(); var format = "image/png"; foreach (var imageFile in imageFiles) { var resizedImageFile = await imageFile.RequestImageFileAsync(format, 100, 100); var buffer = new byte[resizedImageFile.Size]; await resizedImageFile.OpenReadStream().ReadAsync(buffer); var imageDataUrl = $"data:{format};base64,{Convert.ToBase64String(buffer)}"; imageDataUrls.Add(imageDataUrl); } }
}To read data from a user-selected file, you call Code: OpenReadStreamCode: RequestImageFileAsyncCustom validation class attributes in Blazor You can now specify custom validation class names in Blazor. This is useful when integrating with CSS frameworks, like Bootstrap. To specify custom validation class names, create a class derived from Code: FieldCssClassProviderCode: EditContextCode: var editContext = new EditContext(model);
editContext.SetFieldCssClassProvider(new MyFieldClassProvider()); // ... class MyFieldClassProvider : FieldCssClassProvider
{ public override string GetFieldCssClass(EditContext editContext, in FieldIdentifier fieldIdentifier) { var isValid = !editContext.GetValidationMessages(fieldIdentifier).Any(); return isValid ? "legit" : "totally-bogus"; }
}Code: ontoggleBlazor now has support for the Code: ontoggleCode: <div> @if (detailsExpanded) { <p>Read the details carefully!</p> } <details id="details-toggle" @ontoggle="OnToggle"> <summary>Summary</summary> <p>Detailed content</p> </details>
</div> @code { bool detailsExpanded; string message { get; set; } void OnToggle() { detailsExpanded = !detailsExpanded; }
}Thank you Vladimir Samoilenko for this contribution! Model binding Code: DateTimeModel binding in ASP.NET Core now supports correctly binding UTC time strings to Code: DateTimeCode: https://example.com/mycontroller/myaction?time=2019-06-14T02%3A30%3A04.0576719ZCode: DateTimeControl Code: StartupWe’ve provided an additional Code: UseStartupCode: StartupCode: StartupCode: public class Program
{ public static async Task Main(string[] args) { var logger = CreateLogger(); var host = Host.CreateDefaultBuilder() .ConfigureWebHost(builder => { builder.UseStartup(context => new Startup(logger)); }) .Build(); await host.RunAsync(); }
}Open API Specification is a industry-adopted convention for describing HTTP APIs and integrating them into complex business processes or with 3rd parties. Open API is widely supported by all cloud providers and many API registries, so developers who emit Open API documents from their Web APIs have a variety of new opportunities in which those APIs can be used. In partnership with the maintainers of the open-source project Swashbuckle.AspNetCore, we’re excited to announce that the ASP.NET Core API template in RC1 comes pre-wired with a NuGet dependency on Swashbuckle, a popular open-source NuGet package that emits Open API documents dynamically. Swashbuckle does this by introspecting over your API Controllers and generating the Open API document at run-time, or at build time using the Swashbuckle CLI. In .NET 5 RC1, running Code: dotnet new webapiCode: dotnet new webapi --no-openapi trueCode: .csprojCode: <ItemGroup> <PackageReference Include="Swashbuckle.AspNetCore" Version="5.5.1" />
</ItemGroup>In addition to the NuGet package reference being in the Code: .csprojCode: ConfigureServicesCode: Startup.csCode: public void ConfigureServices(IServiceCollection services)
{ services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebApplication1", Version = "v1" }); });
}The Code: ConfigureCode: public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{ if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebApplication1 v1")); } // ...
}When ASP.NET Core API projects are wired to output Open API in this way, the Visual Studio 2019 version 16.8 Preview 2.1 publishing experience will automatically offer an additional step in the publishing flow. Developers who use Azure API Management have an opportunity to automatically import their APIs into Azure API Management during the publish flow. This additional publishing step reduces the number of steps HTTP API developers need to execute to get their APIs published and used with Azure Logic Apps or PowerApps. Better F5 Experience for Web API Projects With Open API enabled by default, we were able to significantly improve the F5 experience for Web API developers. With .NET 5 RC1, the Web API template comes pre-configured to load up the Swagger UI page. The Swagger UI page provides both the documentation you’ve added for your API, but enables you to test your APIs with a single click. SignalR parallel hub invocations In .NET 5 RC1, ASP.NET Core SignalR is now capable of handling parallel hub invocations. You can change the default behavior and allow clients to invoke more than one hub method at a time. Code: public void ConfigureServices(IServiceCollection services)
{ services.AddSignalR(options => { options.MaximumParallelInvocationsPerClient = 5; });
}We’re introducing a new package, Code: com.microsoft.signalr.messagepackCode: .withHubProtocol(new MessagePackHubProtocol())Code: HubConnection hubConnection = HubConnectionBuilder.create("http://localhost:53353/MyHub") .withHubProtocol(new MessagePackHubProtocol()) .build();We have added support for configuring Kestrel’s endpoint-specific options via configuration. The endpoint-specific configurations includes the Http protocols used, the TLS protocols used, the certificate selected, and the client certificate mode. You are able to configure the which certificate is selected based on the specified server name as part of the Server Name Indication (SNI) extension to the TLS protocol as indicated by the client. Kestrel’s configuration also support a wildcard prefix in the host name. The example belows shows you how to specify endpoint-specific using a configuration file: Code: { "Kestrel": { "Endpoints": { "EndpointName": { "Url": "https://*", "Sni": { "a.example.org": { "Protocols": "Http1AndHttp2", "SslProtocols": [ "Tls11", "Tls12"], "Certificate": { "Path": "testCert.pfx", "Password": "testPassword" }, "ClientCertificateMode" : "NoCertificate" }, "*.example.org": { "Certificate": { "Path": "testCert2.pfx", "Password": "testPassword" } }, "*": { // At least one subproperty needs to exist per SNI section or it // cannot be discovered via IConfiguration "Protocols": "Http1", } } } } }
}We hope you enjoy this release of ASP.NET Core in .NET 5! We are eager to hear about your experiences with this latest .NET 5 release. Let us know what you think by filing issues on GitHub. Thanks for trying out ASP.NET Core! |