ASP.NET Core and Blazor updates in .NET Core 3.0 Preview 7
.NET Core 3.0 Preview 7 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:
- Latest Visual Studio preview includes .NET Core 3.0 as the default runtime
- Top level ASP.NET Core templates in Visual Studio
- Simplified web templates
- Attribute splatting for components
- Data binding support for TypeConverters and generics
- Clarified which directive attributes expect HTML vs C#
- EventCounters
- HTTPS in gRPC templates
- gRPC Client Improvements
- gRPC Metapackage
- CLI tool for managing gRPC code generation
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 7 install the .NET Core 3.0 Preview 7 SDK
If you’re on Windows using Visual Studio, install the latest preview of Visual Studio 2019.
Note: .NET Core 3.0 Preview 7 requires Visual Studio 2019 16.3 Preview 1, which is now available!
To install the latest client-side Blazor templates also run the following command:
dotnet new -i Microsoft.AspNetCore.Blazor.Templates::3.0.0-preview7.19365.7
Installing the Blazor Visual Studio extension is no longer required and it can be uninstalled if you’ve installed a previous version. Installing the Blazor WebAssembly templates from the command-line is now all you need to do to get them to show up in Visual Studio.
Upgrade an existing project
To upgrade an existing an ASP.NET Core app to .NET Core 3.0 Preview 7, 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 6 project to Preview 7:
- Update Microsoft.AspNetCore.* package references to 3.0.0-preview7.19365.7.
That’s it! You should be ready to go.
Latest Visual Studio preview includes .NET Core 3.0 as the default runtime
The latest preview update for Visual Studio (16.3) includes .NET Core 3.0 as the default .NET Core runtime version. This means that if you install the latest preview of Visual Studio then you already have .NET Core 3.0. New project by default will target .NET Core 3.0
Top level ASP.NET Core templates in Visual Studio
The ASP.NET Core templates now show up as top level templates in Visual Studio in the “Create a new project” dialog.
This means you can now search for the various ASP.NET Core templates and filter by project type (web, service, library, etc.) to find the one you want to use.
Simplified web templates
We’ve taken some steps to further simplify the web app templates to reduce the amount of code that is frequently just removed.
Specifically:
- The cookie consent UI is no longer included in the web app templates by default.
- Scripts and related static assets are now referenced as local files instead of using CDNs based on the current environment.
We will provide samples and documentation for adding these features to new apps as needed.
Attribute splatting for components
Components can now capture and render additional attributes in addition to the component’s declared parameters. Additional attributes can be captured in a dictionary and then “splatted” onto an element as part of the component’s rendering using the new @attributes
Razor directive. This feature is especially valuable when defining a component that produces a markup element that supports a variety of customizations. For instance if you were defining a component that produces an <input>
element, it would be tedious to define all of the attributes <input>
supports like maxlength
or placeholder
as component parameters.
Accepting arbitrary parameters
To define a component that accepts arbitrary attributes define a component parameter using the [Parameter]
attribute with the CaptureUnmatchedValues
property set to true. The type of the parameter must be assignable from Dictionary<string, object>
. This means that IEnumerable<KeyValuePair<string, object>>
or IReadOnlyDictionary<string, object>
are also options.
@code {
[Parameter(CaptureUnmatchedValues= true)]
Dictionary<string, object> Attributes { get; set; }
}
The CaptureUnmatchedValues
property on [Parameter]
allows that parameter to match all attributes that do not match any other parameter. A component can only define a single parameter with CaptureUnmatchedValues
.
Using @attributes to render arbitrary attributes
A component can pass arbitrary attributes to another component or markup element using the @attributes
directive attribute. The @attributes
directive allows you to specify a collection of attributes to pass to a markup element or component. This is valuable because the set of key-value-pairs specified as attributes can come from a .NET collection and do not need to be specified in the source code of the component.
<input class="form-field" @attributes="Attributes" type="text" />
@code {
[Parameter(CaptureUnmatchedValues = true)]
Dictionary<string, object> Attributes { get; set; }
}
Using the @attributes
directive the contents of the Attribute
property get “splatted” onto the input element. If this results in duplicate attributes, then evaluation of attributes occurs from left to right. In the above example if Attributes
also contained a value for class
it would supersede class="form-field"
. If Attributes
contained a value for type
then that would be superseded by type="text"
.
Data binding support for TypeConverters and generics
Blazor now supports data binding to types that have a string TypeConverter
. Many built-in framework types, like Guid
and TimeSpan
have a string TypeConverter
, or you can define custom types with a string TypeConverter
yourself. These types now work seamlessly with data binding:
<input @bind="guid" />
<p>@guid</p>
@code {
Guid guid;
}
Data binding also now works great with generics. In generic components you can now bind to types specified using generic type parameters.
@typeparam T
<input @bind="value" />
<p>@value</p>
@code {
T value;
}
Clarified which directive attributes expect HTML vs C#
In Preview 6 we introduced directive attributes as a common syntax for Razor compiler related features like specifying event handlers (@onclick
) and data binding (@bind
). In this update we’ve cleaned up which of the built-in directive attributes expect C# and HTML. Specifically, event handlers now expect C# values so a leading @
character is no longer required when specifying the event handler value:
@* Before *@
<button @onclick="@OnClick">Click me</button>
@* After *@
<button @onclick="OnClick">Click me</button>
EventCounters
In place of Windows perf counters, .NET Core introduced a new way of emitting metrics via EventCounters. In preview7, we now emit EventCounters ASP.NET Core. You can use the dotnet counters
global tool to view the metrics we emit.
Install the latest preview of dotnet counters
by running the following command:
dotnet tool install --global dotnet-counters --version 3.0.0-preview7.19365.2
Hosting
The Hosting EventSourceProvider (Microsoft.AspNetCore.Hosting
) now emits the following request counters:
requests-per-second
total-requests
current-requests
failed-requests
SignalR
In addition to hosting, SignalR (Microsoft.AspNetCore.Http.Connections
) also emits the following connection counters:
connections-started
connections-stopped
connections-timed-out
connections-duration
To view all the counters emitted by ASP.NET Core, you can start dotnet counters and specify the desired provider. The example below shows the output when subscribing to events emitted by the Microsoft.AspNetCore.Hosting
and System.Runtime
providers.
dotnet counters monitor -p <PID> Microsoft.AspNetCore.Hosting System.Runtime
New Package ID for SignalR’s JavaScript Client in NPM
The Azure SignalR Service made it easier for non-.NET developers to make use of SignalR’s real-time capabilities. A frequent question we would get from potential customers who wanted to enable their applications with SignalR via the Azure SignalR Service was “does it only work with ASP.NET?” The former identity of the ASP.NET Core SignalR – which included the @aspnet
organization on NPM, only further confused new SignalR users.
To mitigate this confusion, beginning with 3.0.0-preview7, the SignalR JavaScript client will change from being @aspnet/signalr
to @microsoft/signalr
. To react to this change, you will need to change your references in package.json files, require statements, and ECMAScript import statements. If you’re interested in providing feedback on this move or to learn the thought process the team went through to make the change, read and/or contribute to this GitHub issue where the team engaged in an open discussion with the community.
New Customizable SignalR Hub Method Authorization
With Preview 7, SignalR now provides a custom resource to authorization handlers when a hub method requires authorization. The resource is an instance of HubInvocationContext
. The HubInvocationContext
includes the HubCallerContext
, the name of the hub method being invoked, and the arguments to the hub method.
Consider the example of a chat room allowing multiple organization sign-in via Azure Active Directory. Anyone with a Microsoft account can sign in to chat, but only members of the owning organization should be able to ban users or view users’ chat histories. Furthermore, we might want to restrict certain functionality from certain users. Using the updated features in Preview 7, this is entirely possible. Note how the DomainRestrictedRequirement
serves as a custom IAuthorizationRequirement
. Now that the HubInvocationContext
resource parameter is being passed in, the internal logic can inspect the context in which the Hub is being called and make decisions on allowing the user to execute individual Hub methods.
public class DomainRestrictedRequirement :
AuthorizationHandler<DomainRestrictedRequirement, HubInvocationContext>,
IAuthorizationRequirement
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
DomainRestrictedRequirement requirement,
HubInvocationContext resource)
{
if (IsUserAllowedToDoThis(resource.HubMethodName, context.User.Identity.Name) &&
context.User != null &&
context.User.Identity != null &&
context.User.Identity.Name.EndsWith("@jabbr.net", StringComparison.OrdinalIgnoreCase))
{
context.Succeed(requirement);
}
return Task.CompletedTask;
}
private bool IsUserAllowedToDoThis(string hubMethodName,
string currentUsername)
{
return !(currentUsername.Equals("bob42@jabbr.net", StringComparison.OrdinalIgnoreCase) &&
hubMethodName.Equals("banUser", StringComparison.OrdinalIgnoreCase));
}
}
Now, individual Hub methods can be decorated with the name of the policy the code will need to check at run-time. As clients attempt to call individual Hub methods, the DomainRestrictedRequirement
handler will run and control access to the methods. Based on the way the DomainRestrictedRequirement
controls access, all logged-in users should be able to call the SendMessage
method, only users who’ve logged in with a @jabbr.net
email address will be able to view users’ histories, and – with the exception of bob42@jabbr.net
– will be able to ban users from the chat room.
[Authorize]
public class ChatHub : Hub
{
public void SendMessage(string message)
{
}
[Authorize("DomainRestricted")]
public void BanUser(string username)
{
}
[Authorize("DomainRestricted")]
public void ViewUserHistory(string username)
{
}
}
Creating the DomainRestricted
policy is as simple as wiring it up using the authorization middleware. In Startup.cs
, add the new policy, providing the custom DomainRestrictedRequirement
requirement as a parameter.
services
.AddAuthorization(options =>
{
options.AddPolicy("DomainRestricted", policy =>
{
policy.Requirements.Add(new DomainRestrictedRequirement());
});
});
It must be noted that in this example, the DomainRestrictedRequirement
class is not only a IAuthorizationRequirement
but also it’s own AuthorizationHandler
for that requirement. It is fine to split these into separate classes to separate concerns. Yet, in this way, there’s no need to inject the AuthorizationHandler
during Startup
, since the requirement and the handler are the same thing, there’s no need to inject the handler separately.
HTTPS in gRPC templates
The gRPC templates have been now been updated to use HTTPS by default. At development time, we continue the same certificate generated by the dotnet dev-certs
tool and during production, you will still need to supply your own certificate.
gRPC Client Improvements
The managed gRPC client (Grpc.Net.Client
) has been updated to target .NET Standard 2.1 and no longer depends on types present only in .NET Core 3.0. This potentially gives us the ability to run on other platforms in the future.
gRPC Metapackage
In 3.0.0-preview7, we’ve introduced a new package Grpc.AspNetCore
that transitively references all other runtime and tooling dependencies required for building gRPC projects. Reasoning about a single package version for the metapackage should make it easier for developers to deal with as opposed multiple dependencies that version independently.
CLI tool for managing gRPC code generation
The new dotnet-grpc
global tool makes it easier to manage protobuf files and their code generation settings. The global tool manages adding and removing protobuf files as well adding the required package references required to build and run gRPC applications.
Install the latest preview of dotnet-grpc
by running the following command:
dotnet tool install --global dotnet-grpc --version 0.1.22-pre2
As an example, you can run following commands to generate a protobuf file and add it to your project for code generation. If you attempt this on a non-web project, we will default to generating a client and add the required package dependencies.
dotnet new proto -o .\Protos\mailbox.proto
dotnet grpc add-file .\Protos\mailbox.proto
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!
35 comments
Awesome post, Blazor kick ass, on the topic of “Clarified which directive attributes expect HTML vs C#” sound awesome, zero redundancy on blazor code. I am a litle lost in Data binding support for TypeConverters and generics
Thanks Jose! The change to the Blazor data binding system is that previously data binding only supported binding to a very small set of types (strings, enums, DateTime). Blazor now supports binding to any type that has a string TypeConverter. Many types in .NET already have a string TypeConverter, like Guid. You can read up on TypeConverters here: https://docs.microsoft.com/en-us/dotnet/api/system.componentmodel.typeconverter?view=netstandard-2.0. I hope this helps!
There’s a space missing before the “–version…” in “dotnet tool install –global dotnet-counters–version 3.0.0-preview7.19365.2”, it should be “dotnet tool install –global dotnet-counters –version 3.0.0-preview7.19365.2”. Hope that helps
Thanks! Should be fixed now.
👍🏽
Is release candidate 1 still scheduled for July?
Hi Endy. Preview 7 is the July release for .NET Core 3.0. It is a “go-live” release which means for the most part it is stable enough for early production use. However, there are several areas in .NET Core 3.0 that we expect some significant changes prior to the release in Sept, specifically WPF, Windows Forms, Blazor and Entity Framework. We don’t expect to have a true release candidate for .NET Core 3.0 until much closer to the final release in Sept.
>.NET Core 3.0 Preview 7 requires Visual Studio 2019 16.3 Preview 1, which is being released later this week.
The dotnet core SDK download page says v3.0.0-preview7 “Supports Visual Studio 2019 (v16.2. latest preview)”.
https://dotnet.microsoft.com/download/dotnet-core/3.0
Which one is correct?
me too, it’s showing 16.2 preview 4. Is there any update on this Daniel so we can go ahead? Thank you.
.NET Core 3.0 Preview 7 does require Visual Studio 2019 16.3 Preview 1, so it looks like the .NET website needs a quick update. I’ll follow up on that.
The good news is that the the Visual Studio 2019 16.3 Preview 1 release is expected to release later today. Sorry about the delay!
Visual Studio 2019 16.3 Preview 1 is now available! https://devblogs.microsoft.com/visualstudio/visual-studio-2019-version-16-2-generally-available-and-16-3-preview-1/. Update and enjoy!
Any news on client-side Blazor?
Nothing major, as most of our focus right now is on getting .NET Core 3.0 ready to ship. But we did update the .NET WebAssembly support, which comes with some incremental improvements to performance and debugging functionality.
Regarding templates, are there any docs that explain how to get our own templates to work with new VS Create Project Dialog? Also, can you provide a link to the ASP.NET Core templates mentioned in blog so we can use as a reference? Thanks and good job on recent preview bits 🙂
To get templates to show up in the new project dialog you’ll need to use standard Visual Studio extensibility for authoring templates. What’s new is that you can author .NET Core web templates that can show up in the New ASP.NET Core Web App dialog by simply installing the templates from the command line using `dotnet new -i <package ID>`. There aren’t any public docs yet on how to do this, but you can take a look at the Blazor WebAssembly template source to get an idea of what is requried: https://github.com/aspnet/AspNetCore/tree/master/src/Components/Blazor/Templates/src
Hi Daniel! Please tell the team they did an awesome job! Published my app to azure now with preview 7 extensions. Played with B2C authentication as well.
Can you tell me where I can report issues? I found an issue when you add .razor page with the same name as your projects (and a using statement referencing for example the Data namespece, the namespace recognition is messed up and you end up with several errors, not knowing where they come from 🙂 Anyway I figured out what it is so I know what to do and have steps to reproduce it:
1. Create a new project
dotnet new blazorserverside -o <someproject>
2. In the Pages folder add a razor page with the exact same name as <someproject>
Add a @page “/gotothispage”
add a @using <someproject>.Data
3. Compile
You end up with a lot of namespace errors.
Hi Dimitri. Thanks for trying out Blazor! You can report Blazor issues in the ASP.NET Core repo: https://github.com/aspnet/aspnetcore/issues. I went ahead and opened an issue based on the details you provided here: https://github.com/aspnet/AspNetCore/issues/12517. Please look it over and add any additional details that I missed.
HI Daniel, thanks. I have looked at your issue post. I am good with the description. I start following it up there. Blazor is an awesome framework, I am looking forward to its final release!
Hi Dan,
Myself and my team have been looking forward to each update on Blazor, thanks for amazing work.
First thing came to our attention is, intellisense stopped working with VS Preview 16.3 and preview 7. I was wondering if we are missing anything?
I also wanted to share some experiments: running a Blazor client side application in a docker container. I am happy to provide with the details if anyone wants to hear more.
Hmm, intellisense should still work. Please confirm you have Visual Studio 16.3 Preview 1 and the output of `dotnet –version` is 3.0.100-preview7-012821.
We’d love to hear about your Docker exploits! Feel free to open an issue on GitHub (https://github.com/aspnet/aspnetcore/issues) and share any feedback that you might have.
Hi,
Yes it is VS 2019 16.3 Preview. I figured it out, not sure why sometimes the page loses the formatting and intellisense for no reason. But if you close the page and open it again, everything work perfectly.
Our first Blazor client application is going into production next week. It is very exciting. I will share the experience and feedback from the dev team and users.
Many thanks.
Good stuff!
About the additional attributes support, I can’t seem to find
CaptureUnmatchedAttributes
on the parameter attribute. But there is aCaptureUnmatchedValues
. Is it a typo on the blog post? Or?This was a typo in the blog post. Should be fixed now.
Strange, but in
[<code>Parameter(CaptureUnmatchedAttributes = true)]</code>
the<code>CaptureUnmatchedAttributes</code>
property does not exist. butCaptureUnmatchedValues
does.Sorry about that! It was a typo in the blog post. CaptureUnmatchedValues is the correct property name.