![]() |
|
ASP.NET Core and Blazor updates in .NET Core 3.0 Preview 6 - 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 and Blazor updates in .NET Core 3.0 Preview 6 (/thread-90846.html) |
ASP.NET Core and Blazor updates in .NET Core 3.0 Preview 6 - xSicKxBot - 06-14-2019 ASP.NET Core and Blazor updates in .NET Core 3.0 Preview 6 Daniel June 12th, 2019 .NET Core 3.0 Preview 6 is now available and it includes a bunch of new updates to ASP.NET Core and Blazor. 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 6 install the .NET Core 3.0 Preview 6 SDK If you’re on Windows using Visual Studio, you also need to install the latest preview of Visual Studio 2019. For the latest client-side Blazor templates also install the latest Blazor extension from the Visual Studio Marketplace. Upgrade an existing project To upgrade an existing an ASP.NET Core app to .NET Core 3.0 Preview 6, 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 5 project to Preview 6:
Before Code: app.UseRouting(); app.UseEndpoints(endpoints =>
{ endpoints.MapDefaultControllerRoute();
}); app.UseBlazor<Client.Startup>();After Code: app.UseClientSideBlazorFiles<Client.Startup>(); app.UseRouting(); app.UseEndpoints(endpoints =>
{ endpoints.MapDefaultControllerRoute(); endpoints.MapFallbackToClientSideBlazor<Client.Startup>("index.html");
});We’ve added support for the following new Razor language features in this release. Code: @attributeThe new Code: @attributeCode: @attribute [Authorize]Code: @codeThe new Code: @codeCode: @functionsCode: @code { int currentCount = 0; void IncrementCount() { currentCount++; }
}Code: @keyThe new Code: @keyCode: @foreach (var flight in Flights) { }To understand why this feature is needed, consider rendering a list of cards with flight details without this feature: Code: @foreach (var flight in Flights) { }If you add a new flight into the middle of the Code: FlightsCode: DetailsCardCode: DetailsCardTo visualize this, if Code: FlightsCode: [F0, F1, F2]
… and this is the desired after state, given we insert a new item Code: FNew
However, the actual after state this:
The system has no way to know that DetailsCard2 or DetailsCard3 should preserve their associations with their older Flight instances, so it just re-associates them with whatever Flight matches their position in the list. As a result, DetailsCard1 and DetailsCard2 rebuild themselves completely using new data, which is wasteful and sometimes even leads to user-visible problems (e.g., input focus is unexpectedly lost). By adding keys using Code: @keyCode: @namespaceSpecifies the namespace for the generated class or the namespace prefix when used in an _Imports.razor file. The Code: @namespaceCode: @namespace MyNamespaceCode: @functionsIn views and pages (.cshtml files) you can now add markup inside of methods in the Code: @functionsCode: @{ GreetPerson(person); } @functions { void GreetPerson(Person person) { <p>Hello, <em>@person.Name!</em></p> }
}Blazor uses a variety of attributes for influencing how components get compiled (e.g. ref, bind, event handlers, etc.). These attributes have been added organically to Blazor over time and use different syntaxes. In this Blazor release we’ve standardized on a common syntax for directive attributes. This makes the Razor syntax used by Blazor more consistent and predictable. It also paves the way for future extensibility. Directive attributes all follow the following syntax where the values in parenthesis are optional: Code: @directive(-suffix(:name))(="value")Some valid examples: Code: <!-- directive -->
...
<!-- directive with key/value arg-->
...
<!-- directive with suffix -->
<!-- directive with suffix and key/value arg-->All of the Blazor built-in directive attributes have been updated to use this new syntax as described below. Event handlers Specifying event handlers in Blazor now uses the new directive attribute syntax instead of the normal HTML syntax. The syntax is similar to the HTML syntax, but now with a leading Code: @Code: <button @onclick="@Clicked">Click me!</button>When specifying a delegate for C# event handler the Code: @In the future we also expect to use the directive attribute syntax to support additional features for event handlers. For example, stopping event propagation will likely look something like this (not implemented yet, but it gives you an idea of scenarios now enabled by directive attributes): Code: <button @onclick="Clicked" @onclick:stopPropagation>Click me!</button>Bind Code: <input @bind="myValue">...</input>
<input @bind="myValue" @bind:format="mm/dd">...</input>
<MyButton @bind-Value="myValue">...</MyButton>Key Code: ...Ref Code: <button @ref="myButton">...</button>Blazor now has built-in support for handling authentication and authorization. The server-side Blazor template now supports options for enabling all of the standard authentication configurations using ASP.NET Core Identity, Azure AD, and Azure AD B2C. We haven’t updated the Blazor WebAssembly templates to support these options yet, but we plan to do so after .NET Core 3.0 has shipped. To create a new Blazor app with authentication enabled:
In the Blazor app, authentication and authorization are configured in the Code: StartupCode: app.UseRouting(); app.UseAuthentication();
app.UseAuthorization(); app.UseEndpoints(endpoints =>
{ endpoints.MapControllers(); endpoints.MapBlazorHub(); endpoints.MapFallbackToPage("/_Host");
});When using ASP.NET Core Identity all of the identity related UI concerns are handled by the framework provided default identity UI. Code: services.AddDefaultIdentity<IdentityUser>() .AddEntityFrameworkStores<ApplicationDbContext>();The authentication related links in top row of the app are rendered using the new built-in Code: AuthorizeViewLoginDisplay.razor Code: <AuthorizeView> <Authorized> <a href="Identity/Account/Manage">Hello, @context.User.Identity.Name!</a> <a href="Identity/Account/LogOut">Log out</a> </Authorized> <NotAuthorized> <a href="Identity/Account/Register">Register</a> <a href="Identity/Account/Login">Log in</a> </NotAuthorized>
</AuthorizeView>The Code: AuthorizeViewCode: AuthorizeViewCode: AuthorizedCode: NotAuthorizedCode: AuthorizingCode: contextCode: AuthorizeViewTo authorize access to specific pages in a Blazor app, use the normal Code: [Authorize]Code: [Authorize]Code: @attributeCode: @using Microsoft.AspNetCore.Authorization
@attribute [Authorize]
@page "/fetchdata"To specify what content to display on a page that requires authorization when the user isn’t authorized or is still in the processing of authorizing, use the Code: NotAuthorizedContentCode: AuthorizingContentCode: RouterCode: RouterThe new Code: AuthenticationStateProviderCode: AuthenticationStateProviderCode: HttpContextCode: AuthenticationStateProviderThe authentication state is made available to the app as a cascading value ( Code: Task<AuthenticationState>Code: CascadingAuthenticationStateCode: AuthorizeViewCode: RouterApp.razor Code: <CascadingAuthenticationState> <Router AppAssembly="typeof(Startup).Assembly"> <NotFoundContent> <p>Sorry, there's nothing at this address.</p> </NotFoundContent> </Router>
</CascadingAuthenticationState>Razor class libraries can now include static assets like JavaScript, CSS, and images. These static assets can then be included in ASP.NET Core apps by referencing the Razor class library project or via a package reference. To include static assets in a Razor class library add a wwwroot folder to the Razor class library and include any required files in that folder. When a Razor class library with static assets is referenced either as a project reference or as a package, the static assets from the library are made available to the app under the path prefix _content/{LIBRARY NAME}/. The static assets stay in their original folders and any changes to the content of static assets in the Razor class libraries are reflected in the app without rebuilding. When the app is published, the companion assets from all referenced Razor class libraries are copied into the wwwroot folder of the published app under the same prefix. To try out using static assets from a Razor class library:
Projects now use System.Text.Json by default New ASP.NET Core projects will now use System.Text.Json for JSON handling by default. In this release we removed Json.NET (Newtonsoft.Json) from the project templates. To enable support for using Json.NET, add the Microsoft.AspNetCore.Mvc.NewtonsoftJson package to your project and add a call to Code: AddNewtonsoftJson()Code: Startup.ConfigureServicesCode: services.AddMvc() .AddNewtonsoftJson();Preview 6 brings Certificate and Kerberos authentication to ASP.NET Core. Certificate authentication requires you to configure your server to accept certificates, and then add the authentication middleware in Code: Startup.ConfigureCode: Startup.ConfigureServicesCode: public void ConfigureServices(IServiceCollection services)
{ services.AddAuthentication( CertificateAuthenticationDefaults.AuthenticationScheme) .AddCertificate(); // All the other service configuration.
} public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{ app.UseAuthentication(); // All the other app configuration.
}Options for certificate authentication include the ability to accept self-signed certificates, check for certificate revocation, and check that the proffered certificate has the right usage flags in it. A default user principal is constructed from the certificate properties, with an event that enables you to supplement or replace the principal. All the options, and instructions on how to configure common hosts for certificate authentication can be found in the documentation. We’ve also extended “Windows Authentication” onto Linux and macOS. Previously this authentication type was limited to IIS and HttpSys, but now Kestrel has the ability to use Negotiate, Kerberos, and NTLM on Windows, Linux, and macOS for Windows domain joined hosts by using the Microsoft.AspNetCore.Authentication.Negotiate nuget package. As with the other authentication services you configure authentication app wide, then configure the service: Code: public void ConfigureServices(IServiceCollection services)
{ services.AddAuthentication(NegotiateDefaults.AuthenticationScheme) .AddNegotiate();
} public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{ app.UseAuthentication(); // All the other app configuration.
}Your host must be configured correctly. Windows hosts must have SPNs added to the user account hosting the application. Linux and macOS machines must be joined to the domain, then SPNs must be created for the web process, as well as keytab files generated and configured on the host machine. Full instructions are given in the documentation. SignalR Auto-reconnect This preview release, available now via Code: npm install @aspnet/signalr@nextCode: withAutomaticReconnect()Code: HubConnectionBuilderCode: const connection = new signalR.HubConnectionBuilder() .withUrl("/chatHub") .withAutomaticReconnect() .build();By passing an array of millisecond-based durations to the method, you can be very granular about how your reconnection attempts occur over time. Code: .withAutomaticReconnect([0, 3000, 5000, 10000, 15000, 30000])
//.withAutomaticReconnect([0, 2000, 10000, 30000]) yields the default behaviorOr you can pass in an implementation of a custom reconnect policy that gives you full control. If the reconnection fails after the 30-second point (or whatever you’ve set as your maximum), the client presumes the connection is offline and stops trying to reconnect. During these reconnection attempts you’ll want to update your application UI to provide cues to the user that the reconnection is being attempted. Reconnection Event Handlers To make this easier, we’ve expanded the SignalR client API to include Code: onreconnectingCode: onreconnectedCode: onreconnectingCode: connection.onreconnecting((error) => { const status = `Connection lost due to error "${error}". Reconnecting.`; document.getElementById("messageInput").disabled = true; document.getElementById("sendButton").disabled = true; document.getElementById("connectionStatus").innerText = status;
});Likewise, the Code: onreconnectedCode: connection.onreconnected((connectionId) => { const status = `Connection reestablished. Connected.`; document.getElementById("messageInput").disabled = false; document.getElementById("sendButton").disabled = false; document.getElementById("connectionStatus").innerText = status;
});Automatic reconnect has been partially documented already in the preview release. Check out the deeper docs on the topic, with more examples and details on usage, at https://aka.ms/signalr/auto-reconnect. Managed gRPC Client In prior previews, we relied on the Code: Grpc.CoreCode: HttpClientTo begin using the new client, add a package reference to Code: Grpc.Net.ClientCode: var httpClient = new HttpClient() { BaseAddress = new Uri("https://localhost:5001") };
var client = GrpcClient.Create<GreeterClient>(httpClient);Building on the opinionated pattern we introduced in Code: HttpClientFactoryCode: Grpc.Net.ClientFactoryCode: Grpc.AspNetCore.Server.ClientFactoryThe Code: Grpc.Net.ClientFactoryCode: Microsoft.Extensions.*In applications that perform service-to-service communication, we often observe that most servers are also clients that consume other services. In these scenarios, we recommend the use of Code: Grpc.AspNetCore.Server.ClientFactoryTo use the client factory, add the appropriate package reference to your project ( Code: Grpc.AspNetCore.Server.FactoryCode: Grpc.Net.ClientFactoryCode: ConfigureServices()Code: services .AddGrpcClient<GreeterClient>(options => { options.BaseAddress = new Uri("https://localhost:5001"); });gRPC exposes a mechanism to intercept RPC invocations on both the client and the server. Interceptors can be used in conjunction with existing HTTP middleware. Unlike HTTP middleware, interceptors give you access to actual request/response objects before serialization (on the client) and after deserialization (on the server) and vice versa for the response. All middlewares run before interceptors on the request side and vice versa on the response side. Client interceptors When used in conjunction with the client factory, you can add a client interceptor as shown below. Code: services .AddGrpcClient<GreeterClient>(options => { options.BaseAddress = new Uri("https://localhost:5001"); }) .AddInterceptor<CallbackInterceptor>();Server interceptors can be registered in Code: ConfigureServices()Code: services .AddGrpc(options => { // This registers a global interceptor options.Interceptors.Add<MaxStreamingRequestTimeoutInterceptor>(TimeSpan.FromSeconds(30)); }) .AddServiceOptions<GreeterService>(options => { // This registers an interceptor for the Greeter service options.Interceptors.Add<UnaryCachingInterceptor>(); });For examples on how to author an interceptors, take a look at these examples in the grpc-dotnet repo. Give feedback We hope you enjoy the new features in this preview release of ASP.NET Core and Blazor! Please let us know what you think by filing issues on GitHub. Thanks for trying out ASP.NET Core and Blazor! Daniel Roth Principal Program Manager, ASP.NET Follow Daniel https://devblogs.microsoft.com/aspnet/author/danroth27/feed/ |