![]() |
|
ASP.NET Core updates in .NET Core 3.0 Preview 4 - 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 Core 3.0 Preview 4 (/thread-89956.html) |
ASP.NET Core updates in .NET Core 3.0 Preview 4 - xSicKxBot - 04-24-2019 ASP.NET Core updates in .NET Core 3.0 Preview 4 Daniel April 18th, 2019 .NET Core 3.0 Preview 4 is now available and it includes a bunch of new updates to ASP.NET Core. Here’s the list of what’s new in this preview:
Please see the release notes for additional details and known issues. Get started To get started with ASP.NET Core in .NET Core 3.0 Preview 4 install the .NET Core 3.0 Preview 4 SDK If you’re on Windows using Visual Studio, you also need to install the latest preview of Visual Studio 2019. If you’re using Visual Studio Code, check out the improved Razor tooling and Blazor support in the C# extension. Upgrade an existing project To upgrade an existing an ASP.NET Core app to .NET Core 3.0 Preview 4, follow the migrations steps in the ASP.NET Core docs. Please also see the full list of breaking changes in ASP.NET Core 3.0. To upgrade an existing ASP.NET Core 3.0 Preview 3 project to Preview 4:
Before: Code: app.UseRouting(routes =>
{ routes.MapRazorPages();
}); app.UseCookiePolicy(); app.UseAuthorization();After: Code: app.UseRouting(); app.UseCookiePolicy(); app.UseAuthorization(); app.UseEndpoints(routes =>
{ routes.MapRazorPages(); routes.MapFallbackToPage();
});For a while, we’ve used the terminology Razor Components in some cases, and Blazor in other cases. This has proven to be confusing, so following a lot of community feedback, we’ve decided to drop the name ASP.NET Core Razor Components, and return to the name Server-side Blazor instead. This emphasizes that Blazor is a single client app model with multiple hosting models:
… but either way, it’s the same programming model. The same Blazor components can be hosted in both environments. In this preview of the .NET Core SDK we renamed the “Razor Components” template back to “Blazor (server-side)” and updated the related APIs accordingly. In Visual Studio the template will still show up as “Razor Components” when using Visual Studio 2019 16.1.0 Preview 1, but it will start showing up as “Blazor (server-side)” in a subsequent preview. We’ve also updated the template to use the new super cool flaming purple Blazor icon. Client-side Blazor on WebAssembly now in official preview We’re also thrilled to announce that client-side Blazor on WebAssembly is now in official preview! Blazor is no longer experimental and we are committing to ship it as a supported web UI framework including support for running client-side in the browser on WebAssembly.
With each preview release of .NET Core 3.0, we will continue to ship preview releases of both server and client-side Blazor. Resolve components based on Code: @usingComponents in referenced assemblies are now always in scope and can be specified using their full type name including the namespace. You no longer need to import components from component libraries using the Code: @addTagHelperFor example, you can add a Code: CounterCode: IndexUse the @using directive to bring component namespaces into scope just like you would in C# code: Code: @using BlazorWebApp1.PagesUse _Imports.razor files to import Razor directives across multiple Razor component files (.razor) in a hierarchical fashion. For example, the following _Imports.razor file applies a layout and adds using statements for all Razor components in a the same folder and in any sub folders: Code: @layout MainLayout
@using Microsoft.AspNetCore.Components.
@using BlazorApp1.DataThis is similar to how you can use _ViewImports.cshtml with Razor views and pages, but applied specifically to Razor component files. New component item template You can now add components to Blazor apps using the new Razor Component item template: Code: dotnet new razorcomponent -n MyComponent1Server-side Blazor apps require an active SignalR connection to the server to function. In this preview, the app will now attempt to reconnect to the server. As long as the state for that client is still in memory, the client session will resume without losing any state. When the client detects that the connection has been lost a default UI is displayed to the user while the client attempts to reconnect: If reconnection failed the user is given the option to retry: To customize this UI define an element with Code: components-reconnect-modal
Stateful reconnection after prerendering Server-side Blazor apps are setup by default to prerender the UI on the server before client connection back to the server is established. This is setup in the _Host.cshtml Razor page: Code: @(await Html.RenderComponentAsync())
</body>In this preview the client will now reconnect back to the server to the same state that was used to prerender the app. If the app state is still in memory it doesn’t need to be rerendered once the SignalR connection is established. Render stateful interactive components from Razor pages and views You can now add stateful interactive components to a Razor page or View. When the page or view renders the component will be prerendered with it. The app will then reconnect to the component state once the client connection has been established as long as it is still in memory. For example, the following Razor page renders a Code: CounterCode: <h1>My Razor Page</h1>
<form> <input type="number" asp-for="InitialCount" /> <button type="submit">Set initial count</button>
</form> @(await Html.RenderComponentAsync<Counter>(new { InitialCount = InitialCount })) @functions { [BindProperty(SupportsGet=true)] public int InitialCount { get; set; }
}Detect when the app is prerendering While a Blazor app is prerendering, certain actions (like calling into JavaScript) are not possible because a connection with the browser has not yet been established. Components may need to render differently when being prerendered. To delay JavaScript interop calls until after the connection with the browser has been established you can now use the Code: OnAfterRenderAsyncTo conditionally render different content based on whether the app is currently being prerendered or not use Code: IsConnectedCode: IComponentContextConfigure the SignalR client for server-side Blazor apps Sometimes you need to configure the SignalR client used by server-side Blazor apps. For example, you might want to configure logging on the SignalR client to diagnose a connection issue. To configure the SignalR client for server-side Blazor apps, add an Code: autostart="false"Code: Blazor.startCode: http://_framework/blazor.server.js
Blazor.start({ configureSignalR: function (builder) { builder.configureLogging(2); // LogLevel.Information } });Preview 4 will improve the developer experience for handling SignalR disconnection and reconnection. Automatic reconnects can be enabled by calling the Code: withAutomaticReconnectCode: const connection = new signalR.HubConnectionBuilder() .withUrl("/chatHub") .withAutomaticReconnect() .build();Without any parameters, Code: withAutomaticReconnect()In order to configure a non-default number of reconnect attempts before failure, or to change the reconnect timing, Code: withAutomaticReconnectCode: const connection = new signalR.HubConnectionBuilder() .withUrl("/chatHub") .withAutomaticReconnect([0, 0, 2000, 5000]) // defaults to [0, 2000, 10000, 30000] .build();Before starting any reconnect attempts, the Code: HubConnectionCode: ReconnectingCode: onreconnectingCode: connection.onreconnecting((error) => { console.assert(connection.state === signalR.HubConnectionState.Reconnecting); document.getElementById("messageInput").disabled = true; const li = document.createElement("li"); li.textContent = `Connection lost due to error "${error}". Reconnecting.`; document.getElementById("messagesList").appendChild(li);
});If the client successfully reconnects within its first four attempts, the Code: HubConnectionCode: ConnectedCode: onreconnectedCode: connection.onreconnected((connectionId) => { console.assert(connection.state === signalR.HubConnectionState.Connected); document.getElementById("messageInput").disabled = false; const li = document.createElement("li"); li.textContent = `Connection reestablished. Connected with connectionId "${connectionId}".`; document.getElementById("messagesList").appendChild(li);
});If the client doesn’t successfully reconnect within its first four attempts, the Code: HubConnectionCode: DisconnectedCode: onclosedCode: connection.onclose((error) => { console.assert(connection.state === signalR.HubConnectionState.Disconnected); document.getElementById("messageInput").disabled = true; const li = document.createElement("li"); li.textContent = `Connection closed due to error "${error}". Try refreshing this page to restart the connection.`; document.getElementById("messagesList").appendChild(li);
})We’re adding some new options for registering MVC’s various features inside Code: ConfigureServicesWhat’s changing We’re adding three new top level extension methods related to MVC features on Code: IServiceCollectionCode: AddMvc()Code: AddMvc()Code: public void ConfigureServices(IServiceCollection services)
{ // Adds support for controllers and API-related features - but not views or pages. // // Used by the API template. services.AddControllers();
}Code: public void ConfigureServices(IServiceCollection services)
{ // Adds support for controllers, API-related features, and views - but not pages. // // Used by the Web Application (MVC) template. services.AddControllersWithViews();
}Code: public void ConfigureServices(IServiceCollection services)
{ // Adds support for Razor Pages and minimal controller support. // // Used by the Web Application template. services.AddRazorPages();
}These new methods can also be combined. This example is equivalent to the current Code: AddMvc()Code: public void ConfigureServices(IServiceCollection services)
{ services.AddControllers(); services.AddRazorPages();
}These methods return an Code: IMvcBuilderCode: AddMvc()We recommend using whichever option feels best based on your needs. Motivations We wanted to provide some more options that represent how users use the product. In particular we’ve received strong feedback from users that want an API-focused flavor of MVC without the overhead for having the ability to serve views and pages. We tried to provide an experience for this in the past through the Code: AddMvcCore()Code: AddMvcCore()Code: AddControllers()In addition to the Code: AddControllers()Code: AddMvc()What’s in AddControllers() Code: AddControllers()
All of these features are included because they fit under the API-focused banner, and they are very much pay-for-play. None of these features proactively interact with the request pipeline, these are activated by attributes on your controller or model class. API Explorer is an slight exception, it is a piece of infrastructure used by OpenAPI libraries and will do nothing without Swashbuckle or NSwag. Some notable features Code: AddMvc()Code: AddControllers()
These features are view-related and aren’t necessary in an API-focused profile of MVC. What’s in AddControllersWithViews() Code: AddControllersWithViews()
We wanted to position Code: AddControllersWithViews()Code: AddControllers()Some notable features Code: AddMvc()Code: AddControllersWithViews()– Pages What’s in AddRazorPages() Code: AddRazorPages()
For now this profile includes basic support for controllers, but excludes many of the API-focused features listed below. We’re interested in your feedback about what should be included by default in Code: AddRazorPages()Some notable features Code: AddMvc()Code: AddRazorPages()
Endpoint Routing updates In ASP.NET Core 2.2 we introduced a new routing implementation called Endpoint Routing which replaces Code: IRouterWhile it’s still possible to use the old Code: UseMvc()Code: UseRouter()We’ll be uploading another post soon with a conceptual overview and cookbook for Endpoint Routing in 3.0. Endpoint Routing overview Endpoint Routing is made up of the pair of middleware created by Code: app.UseRouting()Code: app.UseEndpoints()Code: app.UseRouting()Code: app.UseEndpoints()If you’re familiar with routing from using MVC then most of what you have experienced so far will behave the same way. Endpoint Routing understands the same route template syntax and processes URLs in a very similar way to the in-the-box implementations of Code: IRouterCode: [Route]We expect most applications will only require changes to the Code: Startup.csA typical Code: Configure()Code: public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{ // Middleware that run before routing. Usually the following appear here: if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } else { app.UseExceptionHandler("/Error"); } app.UseStaticFiles() // Runs matching. An endpoint is selected and set on the HttpContext if a match is found. app.UseRouting(); // Middleware that run after routing occurs. Usually the following appear here: app.UseAuthentication() app.UseAuthorization() app.UseCors() // These middleware can take different actions based on the endpoint. // Executes the endpoint that was selected by routing. app.UseEndpoints(endpoints => { // Mapping of endpoints goes here: endpoints.MapControllers() endpoints.MapRazorPages() endpoints.MapHub<MyChatHub>() endpoints.MapGrpcService<MyCalculatorService>() }); // Middleware here will only run if nothing was matched.
}MVC Controllers, Razor Pages, SignalR, gRPC, and more are added inside Code: UseEndpoints()New template for gRPC The gRPC template has been simplified to a single project template. We no longer include a gRPC client as part of the template. For instructions on how to create a gRPC client, refer to the docs. Code: .
├── appsettings.Development.json
├── appsettings.json
├── grpc.csproj
├── Program.cs
├── Properties
│ └── launchSettings.json
├── Protos
│ └── greet.proto
├── Services
│ └── GreeterService.cs
└── Startup.cs 3 directories, 8 filesDesign-time build support for gRPC code-generation makes it easier to rapidly iterate on your gRPC services. Changes to your Code: *.protoWorker SDK In Preview 3 we introduced the new Worker Service template. In Preview 4 we’ve further decoupled that template from Web by introducing its own SDK. If you create a new Worker Service your csproj will now look like the following: Code: <Project Sdk="Microsoft.NET.Sdk.Worker"> <PropertyGroup> <TargetFramework>netcoreapp3.0</TargetFramework> <UserSecretsId>dotnet-WebApplication59-A2B1DB8D-0408-4583-80BA-1B32DAE36B97</UserSecretsId> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.Extensions.Hosting" Version="3.0.0-preview4.19216.2" /> </ItemGroup>
</Project>We’ll have more to share on the new Worker SDK in a future post. Give feedback We hope you enjoy the new features in this preview release of ASP.NET Core! Please let us know what you think by filing issues on GitHub. Daniel Roth Principal Program Manager, ASP.NET Follow Daniel https://devblogs.microsoft.com/aspnet/author/danroth27/feed/ |