.NET Core 3.0 Preview 2 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:
- Razor Components
- SignalR client-to-server streaming
- Pipes on HttpContext
- Generic host in templates
- Endpoint routing updates
Get started
To get started with ASP.NET Core in .NET Core 3.0 Preview 2 install the .NET Core 3.0 Preview 2 SDK
If you're on Windows using Visual Studio, you'll also want to install the latest preview of Visual Studio 2019.
Upgrade an existing project
To upgrade an existing an ASP.NET Core app to .NET Core 3.0 Preview 2, follow the migrations steps in the ASP.NET Core docs.
Add package for Json.NET
As part of the work to tidy up the ASP.NET Core shared framework, Json.NET is being removed from the shared framework and now needs to be added as a package.
To add back Json.NET support to an ASP.NET Core 3.0 project:
Runtime compilation removed
As a consequence of cleaning up the ASP.NET Core shared framework to not depend on Roslyn, support for runtime compilation of pages and views has also been removed in this preview release. Instead compilation of pages and views is performed at build time. In a future preview update we will provide a NuGet packages for optionally enabling runtime compilation support in an app.
Other breaking changes and announcements
For a full list of other breaking changes and announcements for this release please see the ASP.NET Core Announcements repo.
Build modern web UI with Razor Components
Razor Components are a new way to build interactive client-side web UI with ASP.NET Core. This release of .NET Core 3.0 Preview 2 adds support for Razor Components to ASP.NET Core and for hosting Razor Components on the server. For those of you who have been following along with the experimental Blazor project, Razor Components represent the integration of the Blazor component model into ASP.NET Core along with the server-side Blazor hosting model. ASP.NET Core Razor Components is a new capability in ASP.NET Core to host Razor Components on the server over a real-time connection.
Working with Razor Components
Razor Components are self-contained chunks of user interface (UI), such as a page, dialog, or form. Razor Components are normal .NET classes that define UI rendering logic and client-side event handlers, so you can write rich interactive web apps without having to write any JavaScript. Razor components are typically authored using Razor syntax, a natural blend of HTML and C#. Razor Components are similar to Razor Pages and MVC Views in that they both use Razor. But unlike pages and views, which are built around a request/reply model, components are used specifically for handling UI composition.
To create, build, and run your first ASP.NET Core app with Razor Components run the following from the command line:
dotnet new razorcomponents -o WebApplication1
cd WebApplication1
dotnet run
Or create an ASP.NET Core Razor Components in Visual Studio 2019:
The generated solution has two projects: a server project (WebApplication1.Server), and a project with client-side web UI logic written using Razor Components (WebApplication1.App). The server project is an ASP.NET Core project setup to host the Razor Components.
Why two projects? In part it's to separate the UI logic from the rest of the application. There is also a technical limitation in this preview that we are using the same Razor file extension (.cshtml) for Razor Components that we also use for Razor Pages and Views, but they have different compilation models, so they need to kept separate. In a future preview we plan to introduce a new file extension for Razor Components (.razor) so that you can easily host your components, pages, and views all in the same project.
When you run the app you should see multiple pages (Home, Counter, and Fetch data) on different tabs. On the Counter page you can click a button to increment a counter without any page refresh. Normally this would require writing JavaScript, but here everything is written using Razor Components in C#!
Here's what the Counter
component code looks like:
@page "/counter"
<h1>Counter</h1>
<p>Current count: @currentCount</p>
<button class="btn btn-primary" onclick="@IncrementCount">Click me</button>
@functions {
int currentCount = 0;
void IncrementCount()
{
currentCount+=1;
}
}
Making a request to /counter
, as specified by the @page
directive at the top, causes the component to render its content. Components render into an in-memory representation of the render tree that can then be used to update the UI in a very flexible and efficient way. Each time the "Click me" button is clicked the onclick
event is fired and the IncrementCount
method is called. The currentCount
gets incremented and the component is rendered again. The runtime compares the newly rendered content with what was rendered previously and only the changes are then applied to the DOM (i.e. the updated count).
You can use components from other components using an HTML-like syntax where component parameters are specified using attributes or child content. For example, you can add a Counter
component to the app's home page like this:
@page "/"
<h1>Hello, world!</h1>
Welcome to your new app.
<Counter />
To add a parameter to the Counter
component update the @functions
block to add a property decorated with the [Parameter]
attribute:
@functions {
int currentCount = 0;
[Parameter] int IncrementAmount { get; set; } = 1;
void IncrementCount()
{
currentCount+=IncrementAmount;
}
}
Now you can specify IncrementAmount
parameter value using an attribute like this:
<Counter IncrementAmount="10" />
The Home page then has it's own counter that increments by tens:
This is just an intro to what Razor Components are capable of. Razor Components are based on the Blazor component model and they support all of the same features (parameters, child content, templates, lifecycle events, component references, etc.). To learn more about Razor Components check out the component model docs and try out building your first Razor Components app yourself.
Hosting Razor Components
Because Razor Components decouple a component's rendering logic from how the UI updates get applied, there is a lot of flexibility in how Razor Components can be hosted. ASP.NET Core Razor Components in .NET Core 3.0 adds support for hosting Razor Components on the server in an ASP.NET Core app where all UI updates are handled over a SignalR connection. The runtime handles sending UI events from the browser to the server and then applies UI updates sent by the server back to the browser after running the components. The same connection is also used to handle JavaScript interop calls.
Alternatively, Blazor is an experimental single page app framework that runs Razor Components directly in the browser using a WebAssembly based .NET runtime. In Blazor apps the UI updates from the Razor Components are all applied in process directly to the DOM.
Support for the client-side Blazor hosting model using WebAssembly won't ship with ASP.NET Core 3.0, but we are working towards shipping it with a later release.
Regardless of which hosting model you use for your Razor Components, the component model is the same. The same Razor Components can be used with either hosting model. You can even switch your app back and forth from being a client-side Blazor app or Razor Components running in ASP.NET Core using the same components as long as your components haven't taken any server specific dependencies.
JavaScript interop
Razor Components can also use client-side JavaScript if needed. From a Razor Component you can call into any browser API or into an existing JavaScript library running in the browser. .NET library authors can use JavaScript interop to provide .NET wrappers for JavaScript APIs, so that they can be conveniently called from Razor Components.
public class ExampleJsInterop
{
public static Task<string> Prompt(this IJSRuntime js, string text)
{
return js.InvokeAsync<string>("exampleJsFunctions.showPrompt", text);
}
}
@inject IJSRuntime JS
<button onclick="@OnClick">Show prompt</button>
@functions {
string name
async Task OnClick() {
name = await JS.Prompt("Hi! What's you're name?")
}
}
Both Razor Components and Blazor share the same JavaScript interop abstraction, so .NET libraries relying on JavaScript interop are usable by both types of apps. Check out the JavaScript interop docs for more details on using JavaScript interop and the Blazor community page for existing JavaScript interop libraries.
Sharing component libraries
Components can be easily shared and reused just like you would normal .NET classes. Razor Components can be built into component libraries and then shared as NuGet packages. You can find existing component libraries on the Blazor community page.
The .NET Core 3.0 Preview 2 SDK doesn't include a project template for Razor Component Class Libraries yet, but we expect to add one in a future preview. In meantime, you can use Blazor Component Class Library template.
dotnet new -i Microsoft.AspNetCore.Blazor.Templates::0.8.0-preview-19104-04
dotnet new blazorlib
In this preview release ASP.NET Core Razor Components don't yet support using static assets in component libraries, so the support for component class libraries is pretty limited. However, in a future preview we expect to add this support for using static assets from a library just like you can in Blazor today.
Integration with MVC Views and Razor Pages
Razor Components can be used with your existing Razor Pages and MVC apps. There is no need to rewrite existing views or pages to use Razor Components. Components can be used from within a view or page. When the page or view is rendered, any components used will be prerendered at the same time.
To render a component from a Razor Page or MVC View in this release, use the RenderComponentAsync<TComponent>
HTML helper method:
<div id="Counter">
@(await Html.RenderComponentAsync<Counter>(new { IncrementAmount = 10 }))
</div>
Components rendered from pages and views will be prerendered, but are not yet interactive (i.e. clicking the Counter
button doesn't do anything in this release). This will get addressed in a future preview, along with adding support for rendering components from pages and views using the normal element and attribute syntax.
While views and pages can use components the converse is not true: components can't use views and pages specific features, like partial views and sections. If you want to use a logic from partial view in a component you'll need to factor that logic out first as a component.
Visual Studio 2019 comes with built-in editor support for Razor Components including completions and diagnostics in the editor. You don't need to install any additional extensions.
Razor Component tooling isn't available yet in Visual Studio for Mac or Visual Studio Code, but it's something we are actively working on.
A bright future for Blazor
In parallel with the ASP.NET Core 3.0 work, we will continue ship updated experimental releases of Blazor to support hosting Razor Components client-side in the browser (we'll have more to share on the latest Blazor update shortly!). While in ASP.NET Core 3.0 we will only support hosting Razor Components in ASP.NET Core, we are also working towards shipping Blazor and support for running Razor Components in the browser on WebAssembly in a future release.
SignalR client-to-server streaming
With ASP.NET Core SignalR we added Streaming support, which enables streaming return values from server-side methods. This is useful for when fragments of data will come in over a period of time.
With .NET Core 3.0 Preview 2 we've added client-to-server streaming. With client-to-server streaming, your server-side methods can take instances of a ChannelReader<T>
. In the C# code sample below, the StartStream
method on the Hub will receive a stream of strings from the client.
public async Task StartStream(string streamName, ChannelReader<string> streamContent)
{
while (await streamContent.WaitToReadAsync(Context.ConnectionAborted))
{
while (streamContent.TryRead(out var content))
{
}
}
}
Clients would use the SignalR Subject
(or an RxJS Subject) as an argument to the streamContent
parameter of the Hub method above.
let subject = new signalR.Subject();
await connection.send("StartStream", "MyAsciiArtStream", subject);
The JavaScript code would then use the subject.next
method to handle strings as they are captured and ready to be sent to the server.
subject.next("example")
subject.complete()
Using code like the two snippets above, you can create real-time streaming experiences. For a preview of what you can do with client-side streaming with SignalR, take a look at the demo site, streamr.azurewebsites.net. If you create your own stream, you can stream ASCII art representations of image data being captured by your local web cam to the server, where it will be bounced out to other clients who are watching your stream.
System.IO.Pipelines on HttpContext
In ASP.NET Core 3.0, we're working on consuming the System.IO.Pipelines
API and exposing it in ASP.NET Core to allow you to write more performant applications.
In Preview 2, we're exposing the request body pipe and response body pipe on the HttpContext
that you can directly read from and write to respectively in addition to maintaining the existing Stream-based APIs.
While these pipes are currently just wrappers over the existing streams, we will directly expose the underlying pipes in a future preview.
Here's an example that demonstrates using both the request body and response body pipes directly.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting(routes =>
{
routes.MapGet("/", async context =>
{
await context.Response.WriteAsync("Hello World");
});
routes.MapPost("/", async context =>
{
while (true)
{
var result = await context.Request.BodyPipe.ReadAsync();
var buffer = result.Buffer;
if (result.IsCompleted)
{
break;
}
context.Request.BodyPipe.AdvanceTo(buffer.End);
}
});
});
}
Generic host in templates
The templates have been updated to use the Generic Host instead of WebHostBuilder
as they have in the past:
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
This is part of the ongoing plan started in 2.0 to better integrate ASP.NET Core with other server scenarios that are not web specific.
What about IWebHostBuilder
?
The IWebHostBuilder
interface that is used with WebHostBuilder
today will be kept, and is the type of the webBuilder
used in the sample code above. We intend to deprecate and eventually remove WebHostBuilder
itself as its functionality will be replaced by HostBuilder
, though the interface will remain.
The biggest difference between WebHostBuilder
and HostBuilder
is that you can no longer inject arbitrary services into your Startup.cs
. Instead you will be limited to the IHostingEnvironment
and IConfiguration
interfaces. This removes a behavior quirk related to injecting services into Startup.cs
before the ConfigureServices
method is called. We will publish more details on the differences between WebHostBuilder
and HostBuilder
in a future deep-dive post.
Endpoint routing updates
We're excited to start introducing more of the Endpoint Routing story that began in 2.2. Endpoint routing allows frameworks like MVC as well as other routable things to mix with middleware in a way that hasn't been possible before. This is now present in the project templates in 3.0.0-preview-2, we'll continue to add more richness as we move closer to a final release.
Here's an example:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage()
}
app.UseStaticFiles()
app.UseRouting(routes =>
{
routes.MapApplication()
routes.MapGet("/hello", context =>
{
return context.Response.WriteAsync("Hi there!")
})
routes.MapHealthChecks("/healthz")
})
app.UseAuthentication()
app.UseAuthorization()
}
There's a few things to unpack here.
First, the UseRouting(...)
call adds a new Endpoint Routing middleware. UseRouting
is at the core of many of the templates in 3.0 and replaces many of the features that were implemented inside UseMvc(...)
in the past.
Also notice that inside UseRouting(...)
we're setting up a few things. MapApplication()
brings in MVC controllers and pages for routing. MapGet(...)
shows how to wire up a request delegate to routing. MapHealthChecks(...)
hooks up the health check middleware, but by plugging it into routing.
What might be surprising to see is that some middleware now come after UseRouting
. Let's tweak this example to demonstrate why that is valuable.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage()
}
app.UseStaticFiles()
app.UseRouting(routes =>
{
routes.MapApplication()
routes.MapGet("/hello", context =>
{
return context.Response.WriteAsync("Hi there! Here's your secret message")
})
.RequireAuthorization(new AuthorizeAttribute(){ Roles = "secret-messages", })
routes.MapHealthChecks("/healthz").RequireAuthorization("admin")
})
app.UseAuthentication()
app.UseAuthorization()
}
Now I've added an AuthorizeAttribute
to my request delegate. This is just like placing [Authorize(Roles = "secret-messages")]
on an action method in a controller. We've also given the health checks middleware an authorization policy as well (by policy name).
This works because the following steps happen in order (ignoring what happens before routing):
UseRouting(...)
makes a routing decision – selecting an Endpoint
UseAuthorization()
looks at the Endpoint that was selected and runs the corresponding authorization policy
- hidden… At the end of the middleware pipeline the Endpoint is executed (if no endpoint was matched then a 404 response is returned)
So think of UseRouting(...)
as making a deferred routing decision – where middleware that appear after it run in the middle. Any middleware that run after routing can see the results and read or modify the route data and chosen endpoint. When processing reaches the end of the pipeline, then the endpoint is invoked.
What is an Endpoint and why did we add this?
An Endpoint is a new primitive to help frameworks (like MVC) be friends with middleware. Fundamentally an Endpoint is a request delegate (something that can execute) plus a bag of metadata (policies).
Here's an example middleware – you can use this to examine endpoints in the debugger or by printing to the console:
app.Use(next => (context) =>
{
var endpoint = context.GetEndpoint();
if (endpoint != null)
{
Console.WriteLine("Name: " + endpoint.DisplayName);
Console.WriteLine("Route: " + (endpoint as RouteEndpoint)?.RoutePattern);
Console.WriteLine("Metadata: " + string.Join(", ", endpoint.Metadata));
}
return next(context);
});
In the past we haven't had a good solution when we've wanted to implement a policy like CORS or Authorization in both middleware and MVC. Putting a middleware in the pipeline feels very good because you get to configure the order. Putting filters and attributes on methods in controllers feels really good when you need to apply policies to different parts of the application. Endpoints bring togther all of these advantages.
As an addition problem – what do you do if you're writing the health checks middleware? You might want to secure your middleware in a way that developers can customize. Being able to leverage the ASP.NET Core features for this directly avoids the need to build in support for cross-cutting concerns in every component that serves HTTP.
In addition to removing code duplication from MVC, the Endpoint + Middleware solution can be used by any other ASP.NET Core-based technologies. You don't even need to use UseRouting(...)
– all that is required to leverage the enhancements to middleware is to set an Endpoint on the HttpContext
.
What's integrated with this?
We added the new authorize middleware so that you can start doing more powerful security things with just middleware. The authorize middleware can accept a default policy that applies when there's no endpoint, or the endpoint doesn't specify a policy.
CORS is also now endpoint routing aware and will use the CORS policy specified on an endpoint.
MVC also plugs in to endpoint routing and will create endpoints for all of your controllers and pages. MVC can now be used with the CORS and authorize features and will largely work the same. We've long had confusion about whether to use the CORS middleware or CORS filters in MVC, the updated guidance is to use both. This allows you to provide CORS support to other middleware or static files, while still applying more granular CORS policies with the existing attributes.
Health checks also provide methods to register the health checks middleware as a router-ware (as shown above). This allows you to specify other kinds of policies for health checks.
Finally, new in ASP.NET Core 3.0 preview 2 is host matching for routes. Placing the HostAttribute
on an MVC controller or action will prompt the routing system to require the specified domain or port. Or you can use RequireHost
in your Startup.cs
:
app.UseRouting(routes =>
{
routes.MapGet("/", context => context.Response.WriteAsync("Hi Contoso!"))
.RequireHost("contoso.com")
routes.MapGet("/", context => context.Response.WriteAsync("Hi AdventureWorks!"))
.RequireHost("adventure-works.com")
routes.MapHealthChecks("/healthz").RequireHost("*:8080")
})
Do you think that there are things that are missing from the endpoint story? Are there more things we should make smarter or more integrated? Please let us know what you'd like to see.
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.