ASP.NET Core updates in .NET Core 3.0 Preview 3

Daniel Roth

Daniel

.NET Core 3.0 Preview 3 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 improvements:
    • Single project template
    • New .razor extension
    • Endpoint routing integration
    • Prerendering
    • Razor Components in Razor Class Libraries
    • Improved event handling
    • Forms & validation
  • Runtime compilation
  • Worker Service template
  • gRPC template
  • Angular template updated to Angular 7
  • Authentication for Single Page Applications
  • SignalR integration with endpoint routing
  • SignalR Java client support for long polling

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 3 install the .NET Core 3.0 Preview 3 SDK

If you’re on Windows using Visual Studio, you’ll also want to install the latest preview of Visual Studio 2019.

  • Note: To use use this preview of .NET Core 3.0 with the release channel of Visual Studio 2019, you will need to enable the option to use previews of the .NET Core SDK by going to Tools > Options > Projects and Solutions > .NET Core > Use previews of the .NET Core SDK

Upgrade an existing project

To upgrade an existing an ASP.NET Core app to .NET Core 3.0 Preview 3, 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.

Razor Components improvements

In the previous preview, we introduced Razor Components as a new way to build interactive client-side web UI with ASP.NET Core. This section covers the various improvements we’ve made to Razor Components in this preview update.

Single project template

The Razor Components project template is now a single project instead of two projects in the same solution. The authored Razor Components live directly in the ASP.NET Core app that hosts them. The same ASP.NET Core project can contain Razor Components, Pages, and Views. The Razor Components template also has HTTPS enabled by default like the other ASP.NET Core web app templates.

New .razor extension

Razor Components are authored using Razor syntax, but are compiled differently than Razor Pages and Views. To clarify which Razor files should be compiled as Razor Components we’ve introduced a new file extension: .razor. In the Razor Components template all component files now use the .razor extension. Razor Pages and Views still use the .cshtml extension.

Razor Components can still be authored using the .cshtml file extension as long as those files are identified as Razor Component files using the _RazorComponentInclude MSBuild property. For example, the Razor Component template in this release specifies that all .cshtml files under the Components folder should be treated as Razor Components.

<_RazorComponentInclude>Components\**\*.cshtml</_RazorComponentInclude>

Please note that there are a number of limitations with .razor files in this release. Please refer to the release notes for the list of known issues and available workarounds.

Endpoint routing integration

Razor Components are now integrated into ASP.NET Core’s new Endpoint Routing system. To enable Razor Components support in your application, use MapComponentHub<TComponent> within your routing configuration. For example,

app.UseRouting(routes =>
{
    routes.MapRazorPages();
    routes.MapComponentHub<App>("app");
});

This configures the application to accept incoming connections for interactive Razor Components, and specifies that the root component App should be rendered within a DOM element matching the selector app.

Prerendering

The Razor Components project template now does server-side prerendering by default. This means that when a user navigates to your application, the server will perform an initial render of your Razor Components and deliver the result to their browser as plain static HTML. Then, the browser will reconnect to the server via SignalR and switch the Razor Components into a fully interactive mode. This two-phase delivery is beneficial because:

  • It improves the perceived performance of the site, because the UI can appear sooner, without waiting to make any WebSocket connections or even running any client-side script. This makes a bigger difference for users on slow connections, such as 2G/3G mobiles.
  • It can make your application easily crawlable by search engines.

For users on faster connections, such as intranet users, this feature has less impact because the UI should appear near-instantly regardless.

To set up prerendering, the Razor Components project template no longer has a static HTML file. Instead a single Razor Page, /Pages/Index.cshtml, is used to prerender the app content using the Html.RenderComponentAsync<TComponent>() HTML helper. The page also references the components.server.js script to set up the SignalR connection after the content has been prerendered and downloaded. And because this is a Razor Page, features like the environment tag helper just work.

Index.cshtml

@page "{*clientPath}"
<!DOCTYPE html>
<html>
<head>
    ...
</head>
<body>
    <app>@(await Html.RenderComponentAsync<App>())</app>

    <script src="_framework/components.server.js"></script>
</body>
</html>

Besides the app loading faster, you can see that prerendering is happening by looking at the downloaded HTML source in the browser dev tools. The Razor Components are fully rendered in the HTML.

Razor Components in Razor Class Libraries

You can now add Razor Components to Razor Class Libraries and reference them from ASP.NET Core projects using Razor Components.

To create reusable Razor Components in a Razor Class Library:

  1. Create an Razor Components app:

    dotnet new razorcomponents -o RazorComponentsApp1
    
  2. Create a new Razor Class Library

    dotnet new razorclasslib -o RazorClassLib1
    
  3. Add a Component1.razor file to the Razor Class Library

Component1.razor

<h1>Component1</h1>

<p>@message</p>

@functions {
    string message = "Hello from a Razor Class Library"!;
}
  1. Reference the Razor Class Library from an ASP.NET Core app using Razor Components:

    dotnet add RazorComponentsApp1 reference RazorClassLib1
    
  2. In the Razor Components app, import all components from the Razor Class Library using the @addTagHelper directive and then use Component1 in the app:

Index.razor

@page "/"
@addTagHelper *, RazorClassLib1

<h1>Hello, world!</h1>

Welcome to your new app.

<Component1 />

Note that Razor Class Libraries are not compatible with Blazor apps in this release. Also, Razor Class Libraries do not yet support static assets. To create components in a library that can be shared with Blazor and Razor Components apps you still need to use a Blazor Class Library. This is something we expect to address in a future update.

Improved event handling

The new EventCallback and EventCallback<> types make defining component callbacks much more straightforward. For example consider the following two components:

MyButton.razor

<button onclick="@OnClick">Click here and see what happens!</button>

@functions {
    [Parameter] EventCallback<UIMouseEventArgs> OnClick { get; set; }
}

UsesMyButton.razor

<div>@text</div>

<MyButton OnClick="ShowMessage" />

@function {
    string text;

    void ShowMessage(UIMouseEventArgs e)
    {
        text = "Hello, world!";
    }
}

The OnClick callback is of type EventCallback<UIMouseEventArgs> (instead of Action<UIMouseEventArgs>), which MyButton passes off directly to the onclick event handler. The compiler handles converting the delegate to an EventCallback, and will do some other things to make sure that the rendering process has enough information to render the correct target component. As a result an explicit call to StateHasChanged in the ShowMessage event handler isn’t necessary.

By using the EventCallback<> type OnClick handler can now also be asynchronous without any additional code changes to MyButton:

UsesMyButton.razor

<div>@text</div>

<MyButton OnClick="ShowMessageAsync" />

@function {
    string text;

    async Task ShowMessageAsync(UIMouseEventArgs e)
    {
        await Task.Yield(); 
        text = "Hello, world!";
    }
}

We recommend using EventCallback and EventCallback<T> when you define component parameters for event handling and binding. Use EventCallback<> where possible because it’s strongly typed and will provide better feedback to users of your component. Use EventCallback when there’s no value you will pass to the callback.

Note that consumers don’t have to write different code when using a component because of EventCallback. The same event handling code should still work, while removing some thorny issues and improving the usability of your components.

Forms & validation

This preview release adds built-in components and infrastructure for handling forms and validation.

One of the benefits of using .NET for client-side web development is the ability to share the same implementation logic between the client and the server. Validation logic is a prime example. The new forms & validation support in Razor Components includes support for handling validation using data annotations, or you can plug in your preferred validation system.

For example, the following Person type defines validation logic using data annotations:

public class Person
{
    [Required(ErrorMessage = "Enter a name")]
    [StringLength(10, ErrorMessage = "That name is too long")]
    public string Name { get; set; }

    [Range(0, 200, ErrorMessage = "Nobody is that old")]
    public int AgeInYears { get; set; }

    [Required]
    [Range(typeof(bool), "true", "true", ErrorMessage = "Must accept terms")]
    public bool AcceptsTerms { get; set; }
}

Here’s how you can create a validating form based on this Person model:

<EditForm Model="@person" OnValidSubmit="@HandleValidSubmit">
    <DataAnnotationsValidator />
    <ValidationSummary />

    <p class="name">
        Name: <InputText bind-Value="@person.Name" />
    </p>
    <p class="age">
        Age (years): <InputNumber bind-Value="@person.AgeInYears" />
    </p>
    <p class="accepts-terms">
        Accepts terms: <InputCheckbox bind-Value="@person.AcceptsTerms" />
    </p>

    <button type="submit">Submit</button>
</EditForm>

@functions {
    Person person = new Person();

    void HandleValidSubmit()
    {
        Console.WriteLine("OnValidSubmit");
    }
}

If you add this form to your app and run it you will get a basic form that automatically validates the field inputs when they are changed and when the form is submitted.

Validating form

There are quite a few things going on here, so let’s break it down piece by piece:

  • The form is defined using the new EditForm component. The EditForm sets up an EditContext as a cascading value that tracks metadata about the edit process (e.g. what’s been modified, current validation messages, etc.). The EditForm also provides convenient events for valid and invalid submits (OnValidSubmit, OnInvalidSubmit). Or you can use OnSubmit directly if you want to trigger the validation yourself.
  • The DataAnnotationsValidator component attaches validation support using data annotations to the cascaded EditContext. Enabling support for validation using data annotations currently requires this explicit gesture, but we are considering making this the default behavior that you can then override.
  • Each of the form fields are defined using a set of built-in input components (InputText, InputNumber, InputCheckbox, InputSelect, etc.). These components provide default behavior for validating on edit and changing their CSS class to reflect the field state. Some of them have useful parsing logic (e.g., InputDate and InputNumber handle unparseable values gracefully by registering them as validation errors). The relevant ones also support nullability of the target field (e.g., int?).
  • The ValidationMessage component displays validation messages for a specific field.
  • The ValidationSummary component summarizes all validation messages (similar to the validation summary tag helper).

There are some limitations with the built-in input components that we expect to improve in future updates. For example, you can’t currently specify arbitrary attributes on the generate input tags. In the future, we plan to enable components that pass through all extra attributes. For now, you’ll need to build your own component subclasses to handle these cases.

Runtime compilation

Support for runtime compilation was removed from the ASP.NET Core shared framework in .NET Core 3.0, but you can now enable it by adding a package to your app.

To enable runtime compilation:

  1. Add a package reference to Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation

    <PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" Version="3.0.0-preview3-19153-02" />
    
  2. In Startup.ConfigureServices add a call to AddRazorRuntimeCompilation

    services.AddMvc().AddRazorRuntimeCompilation();
    

Worker Service Template

In 3.0.0-preview3 we are introducing a new template called ‘Worker Service’. This template is designed as a starting point for running long-running background processes like you might run as a Windows Service or Linux Daemon. Examples of this would be producing/consuming messages from a message queue or monitoring a file to process when it appears. It’s intended to provide the productivity features of ASP.NET Core such as Logging, DI, Configuration, etc without carrying any web dependencies.

Worker Service

In the coming days we will publish a few blog posts giving more walkthroughs on using the Worker template to get started. We will have dedicated posts about publishing as a Windows/Systemd service, running on ACI/AKS, as well as running as a WebJob.

Caveats

Whilst the intent is for the worker template to not have any dependencies on web technologies by default, in preview3 it still uses the Web SDK and is shown after you select ‘ASP.NET Core WebApplication’ in Visual Studio. This is temporary and will be changed in a future preview. This means that for preview3 you will see many options in VS that may not make sense, such as publishing your worker as a web app to IIS.

Angular template updated to Angular 7

The Angular template is now updated to Angular 7. We anticipate updating again to Angular 8 before .NET Core 3.0 ships a stable release.

Authentication for the Single Page Application templates

This release introduces support for authentication in our Angular and React templates. In this section we show how to create a new Angular or React template that allows us to authenticate users and access a protected API resource.

Our support for authenticating and authorizing users is powered behind the scenes by IdentityServer, with some extensions we built to simplify the configuration experience for the scenarios we are targeting.

Note: In this post we showcase authentication support for Angular but the React template offers equivalent functionality.

Create a new Angular application

To create a new Angular application with authentication support we invoke the following command:

dotnet new angular -au Individual

This command creates a new ASP.NET Core application with a hosted client Angular application. The ASP.NET Core application includes an Identity Server instance already configured so that your Angular application can authenticate users and send HTTP requests against the protected resources in the ASP.NET Core application.

The authentication and authorization support is built as an Angular module that gets imported into your application and offers a suite of components and services to enhance the functionality of the main applicaiton module.

Run the application

To run the application simply execute the command below and open the browser in the url displayed on the console:

dotnet run
Hosting environment: Development
Content root path: C:\angularapp
Now listening on: https://localhost:5001
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.

SPA index

When we open the application we see the usual Home, Counter and Fetch data menu options and two new options: Register and Login. If we click on Register we get sent to the default Identity UI where (after running migrations and updating the database) we can register as a new user.

Register a new user

SPA register

After registering as a new user we get redirected back to the application where we can see that we are successfully authenticated

SPA logged in

Call an authenticated API

If we click on the Fetch data we can see the weather forecast data table

SPA fetch data

Protect an existing API

To protect an API on the server we simply need to use the [Authorize] attribute on the controller or action that we want to protect.

[Authorize]
[Route("api/[controller]")]
public class SampleDataController : Controller
{
...
}

Require authentication for a client route.

To require the user be authenticated when visiting a page in the Angular application we apply the [AuthorizeGuard] to the route we are configuring.

import { ApiAuthorizationModule } from 'src/api-authorization/api-authorization.module';
import { AuthorizeGuard } from 'src/api-authorization/authorize.guard';
import { AuthorizeInterceptor } from 'src/api-authorization/authorize.interceptor';

@NgModule({
  declarations: [
    AppComponent,
    NavMenuComponent,
    HomeComponent,
    CounterComponent,
    FetchDataComponent
  ],
  imports: [
    BrowserModule.withServerTransition({ appId: 'ng-cli-universal' }),
    HttpClientModule,
    FormsModule,
    ApiAuthorizationModule,
    RouterModule.forRoot([
      { path: '', component: HomeComponent, pathMatch: 'full' },
      { path: 'counter', component: CounterComponent },
      { path: 'fetch-data', component: FetchDataComponent, canActivate: [AuthorizeGuard] },
    ])
  ],
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: AuthorizeInterceptor, multi: true }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Get more details by visiting the docs page

This is a quick introduction to what our new authentication support for Single Page Applications has to offer. For more details check out the docs.

Endpoint Routing with SignalR Hubs

In 3.0.0-preview3 we are hooking SignalR hubs into the new Endpoint Routing feature recently released. SignalR hub wire-up was previously done explicitly:

app.UseSignalR(routes =>
{
    routes.MapHub<ChatHub>("hubs/chat");
});

This meant developers would need to wire up controllers, Razor pages, and hubs in a variety of different places during startup, leading to a series of nearly-identical routing segments:

app.UseSignalR(routes =>
{
    routes.MapHub<ChatHub>("hubs/chat");
});

app.UseRouting(routes =>
{
    routes.MapRazorPages();
});

Now, SignalR hubs can also be routed via endpoint routing, so you’ve got a one-stop place to route nearly everything in ASP.NET Core.

app.UseRouting(routes =>
{
    routes.MapRazorPages();
    routes.MapHub<ChatHub>("hubs/chat");
});

Long Polling for Java SignalR Client

We added long polling support to the Java client which enables it to establish connections even in environments that do not support WebSockets. This also gives you the ability to specifically select the long polling transport in your client apps.

gRPC Template

This preview release introduces a new template for building gRPC services with ASP.NET Core using a new gRPC framework we are building in collaboration with Google.

gRPC is a popular RPC (remote procedure call) framework that offers an opinionated contract-first approach to API development. It uses HTTP/2 for transport, Protocol Buffers as the interface description language, and provides features such as authentication, bidirectional streaming and flow control, and cancellation and timeouts.

gRPC template

The templates create two projects: a gRPC service hosted inside ASP.NET Core, and a console application to test it with.

gRPC solution

This is the first public preview of gRPC for ASP.NET Core and it doesn’t implement all of gRPC’s features, but we’re working hard to make the best gRPC experience for ASP.NET possible. Please try it out and give us feedback at grpc/grpc-dotnet on GitHub.

Stay tuned for future blog posts discussing gRPC for ASP.NET Core in more detail.

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
Daniel Roth

Principal Program Manager, ASP.NET

Follow Daniel   

32 comments

  • Ben Hayat
    Ben Hayat

    Hi Dan;

    I just read the docs on Integrating Identity Server4 into Asp.Net Core for V3. Great news.
    I also read the info on both sides (server and client) support when creating Angular or React client apps. And it seems like there are lots of helpers code written to make Angular & React apps quickly with authentication & Authorization. In a way it’s great, but we use Vue Framework and some others might use vanilla JS client apps.

    My question is, are you going to provide us a Vue template as well? If not, Could you please extend the docs, that is not so Angular or React focused and how we should use other client side frameworks to communicate with the Web API and the ASP server, that can talk to any type of SPA not just Angular or React?

    Thanks!
    ..Ben

    • Daniel Roth
      Daniel Roth

      Thanks for this feedback! We have heard other requests to support Vue.js, as well as other frontend JS frameworks. Unfortunately our resource constraints mean that we are limited in the number of frontend JS frameworks that we can support. We just don’t have the resources provide and maintain templates and guidance for all popular JS frameworks. We don’t have plans to add Vue support at this time, but we do monitor the ever changing landscape of frontend JS frameworks and we can adjust as usage changes.

      • Avatar
        Stefan Tsalapatis

        Vue.js is the most progressive JS framework to be included in our ASP.Net Razor applications. Among many .Net developers, I know, Vue.js is considered as the most adequate to refactor legacy web applications. If you don’t support it, then using Angular or React only, we have to go down on the road of separate API and SPA only in JS (no Razor). Then the step for Node.js backend instead .Net core, it is not far away.  If Microsoft believes that this is a wise policy, I can’t say anything else.

      • Ben Hayat
        Ben Hayat

        Hi Dan;
        Thanks for the reply. Let me sort of address our need in a different way and that might be a better way to ask my original question.

        We are building a Web API that will respond to our client which is going to be written in Vue (basically a JS framework rather a specific framework like AG or React or Vue).
        We need to use your new IS4 integration system in two parts:

        a) An easier way to build our own IS4 server along with our Web API server and have the Web API easily integrate with IS4. I think this is something you guys are working on.

        b) Secondly a JS SDK (a vanila JS library that any JS client can use) to talk to the backend IS4 server to authenticate itself, get a token and then use that token for further connection with out Web API.

        If you do this, then there is no need for custome Vue template.

        For example Google Firebase provides and very nice SDK library that we can import, and with a couple of function calls, we can signup a user, login a user and etc. Their SDK does all the work with their back end Auth server. That’s what we need fro you, to give a clean IS4 integration with Web API and JS client.

        I hope this format of the request made it more clear.
        Thank you again Dan!
        ..Ben

  • Avatar
    Hugo Ferreira

    What about In-Process support for multiple applications on the same application pool ?
    There are out there many applications that can not migrate to .NET Core just because of this and build Out-Process is not a viable solution at all as you know is 400% slower.

    • Avatar
      Sourabh Shirhatti [MSFT]

      We will not be adding support for hosting multiple in-process applications in the same application pool. If you are relying on port sharing in IIS it is still possible as you can run a sub-application run a separate ApplicationPool. 

      • Avatar
        Hugo Ferreira

        I can deal with different ports (if that’s a workaround).
        My issue is that for one hand, I need to run the application In-Process (.NET Core In-Process have a similar performance comparing to full .NET Framework but Out-Process is 400% slower) and on the other hand I need share the same App Pool because using dedicated App Pool per application will draw all the server memory to the limit.
        What are my options ?
        Keept forever with full .NET Framework even the application is already fully portable to .NET Core (convert the application to multi-tenancy is not a viable option) ?

    • Avatar
      Glenn Condron

      The Worker template is more about building a long-running application like a Windows Service. The technology used to build it, IHostedService, is a way that you could build something like HangFire to do background processing  within a hosted .NET Core app. But it’s not a library that provides something like Hangfire.

  • Avatar
    Chad Braden

    Having a template using authentication with Angular is a great step. I hope to see one coming for the React templates as well.

  • Avatar
    Muhamad Farihan Badarus Salleh

    Hi Dan,
    Not quite sure how you do the ‘Authentication for Single Page Application templates’…
    I keep getting ‘MissingMethodException: Method not found: ‘Microsoft.EntityFrameworkCore.Metadata.Builders.IndexBuilder Microsoft.EntityFrameworkCore.Metadata.Builders.EntityTypeBuilder`1.HasIndex(System.Linq.Expressions.Expression`1<System.Func`2<!0,System.Object>>)’.
    IdentityServer4.EntityFramework.Extensions.ModelBuilderExtensions+<>c__DisplayClass2_0.<ConfigurePersistedGrantContext>b__0(EntityTypeBuilder<PersistedGrant> grant)’ error.
     
     

  • Avatar
    Daniel Smith

    Now that .razor files have their own extension, does that make it easier to implement code behinds with partial classses?

  • Avatar
    Sebastiao C. Pereira

    I am curious if Microsoft will develop a SSRS ReportViewer for ASP.NET Core?  I did not understand why Microsoft ignores its own product like SSRS and allow only third parties to offer this tool in Core.

    • Avatar
      Daniel Smith

      Hopefully the SSRS team is working on this for WinForms as well.  This will be a major blocker when it comes to porting our .NET apps to .NET Core 3 if the WinForms viewer doesn’t work.

  • Avatar
    David Revoledo

    Awesome, I heard about it last NDC in London and was playing with net core 3 preview since then, looking forward to play a little bit more seriously and carry some of those features to a productive thing finally, 
    One thing I’m wondering is how razor component can expose behavior like a custom event or a method to execute something outside the component itself with this approach.
     
     

  • Avatar
    Hugo Ferreira

    It is possible to share assemblies between w3wp processes for reduce memory usage ?
    Some application with different application pools.

    • Avatar
      David Fowler

      Share which assemblies? The ones in the shared framework are already shared across all w3wp processes. Do you mean your library code?

      • Hugo Ferreira
        Hugo Ferreira

        “Do you mean your library code?”
        Yes. I have several virtual directories (the same .NET application point each one to differente data base), so they share the same assemblies.

  • Avatar
    Mike Wodarczyk

    Is there a place were we can find more details on form validation through Razor components.  For example, how is the component “ValidationMessage” used?  It also looks like the “Submit” button is active even when the form in invalid.  How does one deactivate the “Submit” button for invalid data?  Thanks!

    • Avatar
      Mike Wodarczyk

      Ok.  I decided to try and answer my own question about “ValidationMessage” by looking in the code.  
       
      It looks like the tag needs an attribute named “For” and perhaps a tyoe “T”.  In the example above, it could be used like this:
           <ValidationMessage T=”string” For=”() => person.Name”></ValidationMessage>
      The “For” expression looks like it needs to be a bare function (with no @).

  • Avatar
    Paul Anderson

    Nice work… 
    Is there a demo for Razor Class Library at all?  I am stuggling to get a web application to display razor class library pages in the actual class library.  I’ve created both from the templates in VS2019 Preview and using preview 3.  Not sure what I need to do in order to recognise the class library area pages.  I’ve added a project reference to it as per what I’ve done previously in 2.2.  Now we have end point routing available via services.AddRouting/app.UseRouting and routes => routes.MapRazorPages does not seem to locate them.  Do I need specific configuration?
    Thanks
     

  • Avatar
    Sebastian Redl

    In preview2 there was an IEndpointRouteBuilder.MapApplication extension method. It’s used in the Preview2 announcement example under the “Endpoint routing updates” heading.
    It seems to have disappeared again; after updating to preview3 the method is not found. What’s the replacement?

Leave a comment