Quantcast
Channel: ASP.NET Blog
Viewing all articles
Browse latest Browse all 7144

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

$
0
0

.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.

The post ASP.NET Core updates in .NET Core 3.0 Preview 3 appeared first on ASP.NET Blog.


Viewing all articles
Browse latest Browse all 7144

Trending Articles