ASP.NET Core and Blazor updates in .NET Core 3.0 Preview 9

Daniel Roth

Daniel

.NET Core 3.0 Preview 9 is now available and it contains a number of improvements and updates to ASP.NET Core and Blazor.

Here’s the list of what’s new in this preview:

  • Blazor event handlers and data binding attributes moved to Microsoft.AspNetCore.Components.Web
  • Blazor routing improvements
    • Render content using a specific layout
    • Routing decoupled from authorization
    • Route to components from multiple assemblies
  • Render multiple Blazor components from MVC views or pages
  • Smarter reconnection for Blazor Server apps
  • Utility base component classes for managing a dependency injection scope
  • Razor component unit test framework prototype
  • Helper methods for returning Problem Details from controllers
  • New client API for gRPC
  • Support for async streams in streaming gRPC responses

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

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

.NET Core 3.0 Preview 9 requires Visual Studio 2019 16.3 Preview 3 or later.

To install the latest Blazor WebAssembly template also run the following command:

dotnet new -i Microsoft.AspNetCore.Blazor.Templates::3.0.0-preview9.19424.4

Upgrade an existing project

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

  • Update all Microsoft.AspNetCore.* package references to 3.0.0-preview9.19424.4
  • In Blazor apps and libraries:
    • Add a using statement for Microsoft.AspNetCore.Components.Web in your top level _Imports.razor file (see Blazor event handlers and data binding attributes moved to Microsoft.AspNetCore.Components.Web below for details)
    • Add a using statement for Microsoft.AspNetCore.Components.Authorization in your top level _Imports.razor file. In Blazor WebAssembly apps also add a package reference to Microsoft.AspNetCore.Components.Authorization.
    • Update all Blazor component parameters to be public.
    • Update implementations of IJSRuntime to return ValueTask<T>.
    • Replace calls to MapBlazorHub<TComponent> with a single call to MapBlazorHub.
    • Update calls to RenderComponentAsync and RenderStaticComponentAsync to use the new overloads to RenderComponentAsync that take a RenderMode parameter (see Render multiple Blazor components from MVC views or pages below for details).
    • Update App.razor to use the updated Router component (see Blazor routing improvements below for details).
    • (Optional) Remove page specific _Imports.razor file with the @layout directive to use the default layout specified through the router instead.
    • Remove any use of the PageDisplay component and replace with LayoutView, RouteView, or AuthorizeRouteView as appropriate (see Blazor routing improvements below for details).
    • Replace uses of IUriHelper with NavigationManager.
    • Remove any use of @ref:suppressField.
    • Replace the previous RevalidatingAuthenticationStateProvider code with the new RevalidatingIdentityAuthenticationStateProvider code from the project template.
    • Replace Microsoft.AspNetCore.Components.UIEventArgs with System.EventArgs and remove the “UI” prefix from all EventArgs derived types (UIChangeEventArgs -> ChangeEventArgs, etc.).
    • Replace DotNetObjectRef with DotNetObjectReference.
    • Replace OnAfterRender() and OnAfterRenderAsync() implementations with OnAfterRender(bool firstRender) or OnAfterRenderAsync(bool firstRender).
    • Remove any usage of IComponentContext and move any logic that should not run during prerendering into OnAfterRender or OnAfterRenderAsync.
  • In gRPC projects:
    • Update calls to GrpcClient.Create with a call GrpcChannel.ForAddress to create a new gRPC channel and new up your typed gRPC clients using this channel.
    • Rebuild any project or project dependency that uses gRPC code generation for an ABI change in which all clients inherit from ClientBase instead of LiteClientBase. There are no code changes required for this change.
    • Please also see the grpc-dotnet announcement for all changes.

You should now be all set to use .NET Core 3.0 Preview 9!

Blazor event handlers and data binding attributes moved to Microsoft.AspNetCore.Components.Web

In this release we moved the set of bindings and event handlers available for HTML elements into the Microsoft.AspNetCore.Components.Web.dll assembly and into the Microsoft.AspNetCore.Components.Web namespace. This change was made to isolate the web specific aspects of the Blazor programming from the core programming model. This section provides additional details on how to upgrade your existing projects to react to this change.

Blazor apps

Open the application’s root _Imports.razor and add @using Microsoft.AspNetCore.Components.Web. Blazor apps get a reference to the Microsoft.AspNetCore.Components.Web package implicitly without any additional package references, so adding a reference to this package isn’t necessary.

Blazor libraries

Add a package reference to the Microsoft.AspNetCore.Components.Web package package if you don’t already have one. Then open the root _Imports.razor file for the project (create the file if you don’t already have it) and add @using Microsoft.AspNetCore.Components.Web.

Troubleshooting guidance

With the correct references and using statement for Microsoft.AspNetCore.Components.Web, event handlers like @onclick and @bind should be bold font and colorized as shown below when using Visual Studio.

Events and binding working in Visual Studio

If @bind or @onclick are colorized as a normal HTML attribute, then the @using statement is missing.

Events and binding not recognized

If you’re missing a using statement for the Microsoft.AspNetCore.Components.Web namespace, you may see build failures. For example, the following build error for the code shown above indicates that the @bind attribute wasn’t recognized:

CS0169  The field 'Index.text' is never used
CS0428  Cannot convert method group 'Submit' to non-delegate type 'object'. Did you intend to invoke the method?

In other cases you may get a runtime exception and the app fails to render. For example, the following runtime exception seen in the browser console indicates that the @onclick attribute wasn’t recognized:

Error: There was an error applying batch 2.
DOMException: Failed to execute 'setAttribute' on 'Element': '@onclick' is not a valid attribute name.

Add a using statement for the Microsoft.AspNetCore.Components.Web namespace to address these issues. If adding the using statement fixed the problem, consider moving to the using statement app’s root _Imports.razor so it will apply to all files.

If you add the Microsoft.AspNetCore.Components.Web namespace but get the following build error, then you’re missing a package reference to the Microsoft.AspNetCore.Components.Web package:

CS0234  The type or namespace name 'Web' does not exist in the namespace 'Microsoft.AspNetCore.Components' (are you missing an assembly reference?)

Add a package reference to the Microsoft.AspNetCore.Components.Web package to address the issue.

Blazor routing improvements

In this release we’ve revised the Blazor Router component to make it more flexible and to enable new scenarios. The Router component in Blazor handles rendering the correct component that matches the current address. Routable components are marked with the @page directive, which adds the RouteAttribute to the generated component classes. If the current address matches a route, then the Router renders the contents of its Found parameter. If no route matches, then the Router component renders the contents of its NotFound parameter.

To render the component with the matched route, use the new RouteView component passing in the supplied RouteData from the Router along with any desired parameters. The RouteView component will render the matched component with its layout if it has one. You can also optionally specify a default layout to use if the matched component doesn’t have one.

<Router AppAssembly="typeof(Program).Assembly">
    <Found Context="routeData">
        <RouteView RouteData="routeData" DefaultLayout="typeof(MainLayout)" />
    </Found>
    <NotFound>
        <h1>Page not found</h1>
        <p>Sorry, but there's nothing here!</p>
    </NotFound>
</Router>

Render content using a specific layout

To render a component using a particular layout, use the new LayoutView component. This is useful when specifying content for not found pages that you still want to use the app’s layout.

<Router AppAssembly="typeof(Program).Assembly">
    <Found Context="routeData">
        <RouteView RouteData="routeData" DefaultLayout="typeof(MainLayout)" />
    </Found>
    <NotFound>
        <LayoutView Layout="typeof(MainLayout)">
            <h1>Page not found</h1>
            <p>Sorry, but there's nothing here!</p>
        </LayoutView>
    </NotFound>
</Router>

Routing decoupled from authorization

Authorization is no longer handled directly by the Router. Instead, you use the AuthorizeRouteView component. The AuthorizeRouteView component is a RouteView that will only render the matched component if the user is authorized. Authorization rules for specific components are specified using the AuthorizeAttribute. The AuthorizeRouteView component also sets up the AuthenticationState as a cascading value if there isn’t one already. Otherwise, you can still manually setup the AuthenticationState as a cascading value using the CascadingAuthenticationState component.

<Router AppAssembly="@typeof(Program).Assembly">
    <Found Context="routeData">
        <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
    </Found>
    <NotFound>
        <CascadingAuthenticationState>
            <LayoutView Layout="@typeof(MainLayout)">
                <p>Sorry, there's nothing at this address.</p>
            </LayoutView>
        </CascadingAuthenticationState>
    </NotFound>
</Router>

You can optionally set the NotAuthorized and Authorizing parameters of the AuthorizedRouteView component to specify content to display if the user is not authorized or authorization is still in progress.

<Router AppAssembly="@typeof(Program).Assembly">
    <Found Context="routeData">
        <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
            <NotAuthorized>
                <p>Nope, nope!</p>
            </NotAuthorized>
        </AuthorizeRouteView>
    </Found>
</Router>

Route to components from multiple assemblies

You can now specify additional assemblies for the Router component to consider when searching for routable components. These assemblies will be considered in addition to the specified AppAssembly. You specify these assemblies using the AdditionalAssemblies parameter. For example, if Component1 is a routable component defined in a referenced class library, then you can support routing to this component like this:

<Router
    AppAssembly="typeof(Program).Assembly"
    AdditionalAssemblies="new[] { typeof(Component1).Assembly }>
    ...
</Router>

Render multiple Blazor components from MVC views or pages

We’ve reenabled support for rendering multiple components from a view or page in a Blazor Server app. To render a component from a .cshtml file, use the Html.RenderComponentAsync<TComponent>(RenderMode renderMode, object parameters) HTML helper method with the desired RenderMode.

RenderMode Description Supports parameters?
Static Statically render the component with the specified parameters. Yes
Server Render a marker where the component should be rendered interactively by the Blazor Server app. No
ServerPrerendered Statically prerender the component along with a marker to indicate the component should later be rendered interactively by the Blazor Server app. No

Support for stateful prerendering has been removed in this release due to security concerns. You can no longer prerender components and then connect back to the same component state when the app loads. We may reenable this feature in a future release post .NET Core 3.0.

Blazor Server apps also no longer require that the entry point components be registered in the app’s Configure method. Only a single call to MapBlazorHub() is required.

Smarter reconnection for Blazor Server apps

Blazor Server apps are stateful and require an active connection to the server in order to function. If the network connection is lost, the app will try to reconnect to the server. If the connection can be reestablished but the server state is lost, then reconnection will fail. Blazor Server apps will now detect this condition and recommend the user to refresh the browser instead of retrying to connect.

Blazor Server reconnect rejected

Utility base component classes for managing a dependency injection scope

In ASP.NET Core apps, scoped services are typically scoped to the current request. After the request completes, any scoped or transient services are disposed by the dependency injection (DI) system. In Blazor Server apps, the request scope lasts for the duration of the client connection, which can result in transient and scoped services living much longer than expected.

To scope services to the lifetime of a component you can use the new OwningComponentBase and OwningComponentBase<TService> base classes. These base classes expose a ScopedServices property of type IServiceProvider that can be used to resolve services that are scoped to the lifetime of the component. To author a component that inherits from a base class in Razor use the @inherits directive.

@page "/users"
@attribute [Authorize]
@inherits OwningComponentBase<Data.ApplicationDbContext>

<h1>Users (@Service.Users.Count())</h1>
<ul>
    @foreach (var user in Service.Users)
    {
        <li>@user.UserName</li>
    }
</ul>

Note: Services injected into the component using @inject or the InjectAttribute are not created in the component’s scope and will still be tied to the request scope.

Razor component unit test framework prototype

We’ve started experimenting with building a unit test framework for Razor components. You can read about the prototype in Steve Sanderson’s Unit testing Blazor components – a prototype blog post. While this work won’t ship with .NET Core 3.0, we’d still love to get your feedback early in the design process. Take a look at the code on GitHub and let us know what you think!

Helper methods for returning Problem Details from controllers

Problem Details is a standardized format for returning error information from an HTTP endpoint. We’ve added new Problem and ValidationProblem method overloads to controllers that use optional parameters to simplify returning Problem Detail responses.

[Route("/error")]
public ActionResult<ProblemDetails> HandleError()
{
    return Problem(title: "An error occurred while processing your request", statusCode: 500);
}

New client API for gRPC

To improve compatibility with the existing Grpc.Core implementation, we’ve changed our client API to use gRPC channels. The channel is where gRPC configuration is set and it is used to create strongly typed clients. The new API provides a more consistent client experience with Grpc.Core, making it easier to switch between using the two libraries.

// Old
using var httpClient = new HttpClient() { BaseAddress = new Uri("https://localhost:5001") };
var client = GrpcClient.Create<GreeterClient>(httpClient);

// New
var channel = GrpcChannel.ForAddress("https://localhost:5001");
var client = new GreeterClient(channel);

var reply = await client.GreetAsync(new HelloRequest { Name = "Santa" });

Support for async streams in streaming gRPC responses

gRPC streaming responses return a custom IAsyncStreamReader type that can be iterated on to receive all response messages in a streaming response. With the addition of async streams in C# 8, we’ve added a new extension method that makes for a more ergonomic API while consuming streaming responses.

// Old
while (await requestStream.MoveNext(CancellationToken.None))
{
  var message = requestStream.Current;
  // …
}

// New and improved
await foreach (var message in requestStream.ReadAllAsync())
{
  // …
}

Give feedback

We hope you enjoy the new features in this preview release of ASP.NET Core and Blazor! Please let us know what you think by filing issues on GitHub.

Thanks for trying out ASP.NET Core and Blazor!

Daniel Roth
Daniel Roth

Principal Program Manager, ASP.NET

Follow Daniel   

120 comments

  • Peter albanese
    Peter albanese

    Quick note to those upgrading. Once you update Visual Studio to 2019 16.3 Preview, you don’t need to seperately install .NET Core 3 Preview 9, it appears this version of .NET Core is already included with Visual Studio 16.3

    • Daniel Roth
      Daniel Roth

      The selector based overload to `MapBlazorHub` is no longer needed and has been removed. Instead, you just need a single call to `MapBlazorHub()` and then use `Html.RenderComponentAsync` with the desired RenderMode.

      • Avatar
        Alexandre Reyes

        But I want to disable server side rendering @Daniel, i don’t like to keep validating if javascript is available.

        • Daniel Roth
          Daniel Roth

          Blazor Server apps are generally rendered on the server, so I’m not sure I understand what you mean by disabling it. Could you please clarify what you mean?

          Also, what specifically do you not want to validate? 

          • Daniel Roth
            Daniel Roth

            You can disable prerendering by using RenderMode.Server, which means that only a marker will be put in the initial HTML that will later be updated when the client connection has been established. This is very similar to how things worked when using a static HTML file.

            JS interop should be available in OnAfterRender. However, please note that JS interop calls may still fail in a Blazor Server app  due to other concerns like loss of network connectivity.

          • Avatar
            Guillaume ZAHRA

            Actually, i think removing the overload present in preview8 with MapBlazorHub is a mistake.

            In previous versions, you were able to:

            – Use client-side “index.html” file in server-side mode instead of the CSHTML file.
            – Use another component than “App.razor” as root component.

            Now there is some differences between the client-side and server-side on this point as:

            – Use client-side “index.html” file in server-side mode instead of the CSHTML file. => should still be ok with MapFallbackToClientSideBlazor, even if i didn’t re-tested.
            – Use another component than “App.razor” as root component.  => NOT OK

            But you can still do this apparently on the client-side Startup side.
            It seem to me inconsistent.

            The main problem on my side is that i was able to inherit from App.razor, adding some custom logic and then use my inherited component at startup easily, without decorating any layout or other rendering thing, for managing to load my BlazorMobileComponent class at startup for BlazorMobile.
            Now i cannot inherit this behavior on the server-side project type because of this breaking change.
            Well, i think i will have to search another easy way to do that.

          • Avatar
            Guillaume ZAHRA

            Just to clarify: You can actually do what was present before (even loading the component you want at Startup) in pure server-side mode, but you can’t with client-side fallback, as you cannot inject any @(await Html.RenderComponentAsync<App>(RenderMode.ServerPrerendered)) .

            EDIT: I ended to updating my plugin MSBuild task in order to generate a valid starting *.cshtml file sync from the index.html file in order to workaround this difference.

          • Daniel Roth
            Daniel Roth

            You should be able to render whatever component you want using RenderComponentAsync<TComponent>(…). You can also render multiple different components this way on different parts of the page (this was specifically enabled in Preview 9).

            It would be great to understand your requirements for static HTML in Blazor Server apps. Could you please open an issue on https://github.com/aspnet/aspnetcore/issue on that with details about your scenario and requirements?

  • Peter albanese
    Peter albanese

    Can someone clarify the use case difference between the Microsoft.AspNetCore.Mvc.Rendering.RenderMode Enums? Most notably, the difference between Html.RenderComponentAsync<App>(RenderMode.ServerPrerendered) and Html.RenderComponentAsync<App>(RenderMode.Server)

    • Daniel Roth
      Daniel Roth

      RenderMode.Server will only render a marker where the component should be eventually rendered once the connection has been established.

      RenderMode.ServerPrerendered will prerender the component on the server and add the marker. When the connection gets established, the component is then rerendered and setup for interactivity.

  • Avatar
    FillTable Admin

    For Authorization, need to add @using Microsoft.AspNetCore.Components.Authorization to top level _Imports.razor file

  • Avatar
    Steve Buchok

    Small correction. 
    <Router AppAssembly="typeof(Program).Assembly">
    <Found Context="routeData">
    <RouteView RouteData="routeData" DefaultLayout="typeof(MainLayout)" />
    </Found>
    <NotFound>
    <LayoutView Layout="typeof(MainLayout)">
    <h1>Page not found</h1>
    <p>Sorry, but there's nothing here!</p>
    </Layout>
    </NotFound>
    </Router>

    </Layout> should be </LayoutView> ... pretty sure ;)

  • Avatar
    Mr. Charles

    Hello!! What would be the recommended way to read the parameters from a URL if a blazor component is inside a razor page?
    I have a razor page for example:  test.com/2019/91242
    How can I read these 2 parameters from inside a blazor component without parsing the URL myself?  Until now the razor page passed the parameters using stateful prerendering but now what would be the recommended way to do it?

    Regards!

  • Avatar
    Maxim Rybkov

    After updating SDK and Hosting to Preview 9 getting this error on the form submission InvalidDataException: Form key length limit 2147483647 or value length limit 2147483647 exceeded.Rolling back to Preview 8 solves the issue.

  • Avatar
    Lars vT

    As the update to Preview 16.3 automatically installed the Preview9, how can I rollback to Preview8 to build my current blazor apps without the need to upgrade everything now asap?Problem:Seems to require Microsoft.CodeAnalysis.Common (>= 3.3.0) – but this nuget package is not available, only a “beta2” which wont be accepted. See belowFehler NU1605 Ein Downgrade des Pakets “Microsoft.CodeAnalysis.Common” von 3.3.0 auf 3.3.0-beta2-final wurde festgestellt. Verweisen Sie direkt aus dem Projekt auf das Paket, um eine andere Version auszuwählen. ProjectRatingApp -> Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore 3.0.0-preview9-19453-02 -> Microsoft.VisualStudio.Web.CodeGeneration.Core 3.0.0-preview9-19453-02 -> Microsoft.VisualStudio.Web.CodeGeneration.Templating 3.0.0-preview9-19453-02 -> Microsoft.CodeAnalysis.Razor 3.0.0-preview9.19423.3 -> Microsoft.CodeAnalysis.Common (>= 3.3.0) ProjectRatingApp -> Microsoft.CodeAnalysis.Common (>= 3.3.0-beta2-final)

  • Avatar
    Andrey Kalinovskiy

    Hello
    What about IComponentContext? Now it’s absent in Microsoft.AspNetCore.Components namespace. Thank you.

  • Avatar
    Howard Richards

    There seems to be an ommission in the upgrade process you’ve outlined. I tried to upgrade by chat sample https://github.com/conficient/BlazorChatSample from preview 8 to preview 9. The <Router> changes generated lots of errors (despite the app still compiling) – I found that we have two new packages we need to add:
    Microsoft.AspNetCore.Blazor.HttpClient
    Microsoft.AspNetCore.Blazor.DevServer

    You might want to update the post to cover these off?

    • Avatar
      Lars vT

      Yes, painfull process with lots of erros. Got lost now after upgrading the visual preview to 16.3 – would be really helpfull if someone could tell how to avoid Preview9 is used for all existing projects for build and how to force rollback to preview8 to being able to continue working while upgrading the projects later step by step to Preview9.

      • Avatar
        Deine Mudda

        I don’t think it’s possible to simply downgrade. Install the old version of VS and preview8 and run your project with a previous commit from your git history^^

      • Avatar
        Vladimir Ignatov

        By default dotnet compiler uses the latest SDK, which is in this case 3.0.100-preview9-014004. You can either uninstall it to return back to preview 8  aand then install it back when it is ready, or you can specify in your project whoch SDK to use in global.json file. See here in details: https://docs.microsoft.com/en-us/dotnet/core/versions/selection
        Simply: create global.json file and put into your project root folder. Add the following content:
        {    “sdk”: {      “version”: “3.0.100-preview8-013656”    }  }
        And rebuild your project. You may need to clean and rebuild in order for it to work. My compiler did not pick it up on incremental build.

    • Daniel Roth
      Daniel Roth

      Which migration steps were missing for the Router? Most of the changes should already be covered in the Blazor Router improvements section, but let me know if I missed anything and I’m happy to add it.

      The Microsoft.AspNetCore.Blazor.HttpClient package was actually introduced in Preview 8, not Preview 9, and is covered in the Preview 8 migration guidance. Microsoft.AspNetCore.Blazor.DevServer package was introduced back in Preview 4. 

      • Avatar
        Howard Richards

        I have an demo app that’s working on Preview 8 just fine, it only referenced 
        Microsoft.AspNetCore.Blazor Microsoft.AspNetCore.Blazor.Build
        When upgrade to Preview 9 and did the changes to <Router> I got errors – it didn’t like the new syntax.
        I found that I need to add
        Microsoft.AspNetCore.Blazor.HttpClient Microsoft.AspNetCore.Blazor.DevServer
        As well. Not sure when these libs were introduced but don’t remember them from earlier previews 

      • Avatar
        Howard Richards

        I assume that the router code must have moved to the HttpClient package since I didn’t previously reference it in Preview8, hence the error I got. I expect we can leave the blog post unchanged as people might notice the comments if they too experience errors.

  • Avatar
    Maytham Fahmi

    As I understand Core 3 is supposed to be release end of sept. 2019 (this month) I am starting a new project and would like to go with Blazor. Is Preview 9 would be part of the release with Core 3 end of this month. If not is there minor or major changes coming later? more or less I do not burn fingers.

    • Daniel Roth
      Daniel Roth

      .NET Core 3.0 Preview 9 is the last planned preview release before we ship later this month. We worked pretty hard to get the last batch of Blazor related API changes into Preview 9 and we don’t have plans to make any additional API breaking changes before .NET Core 3.0 ships later this month. It’s a great time to start building with .NET Core 3.0!

  • Avatar
    Michael Washington

    Is there documentation on:
    @inherits OwningComponentBase<Data.ApplicationDbContext>
    The question is, should be used this when using Entity Framework? If we don’t, what happens?

    Thank You

    • Daniel Roth
      Daniel Roth

      Docs on OwningComponentBase are coming shortly. Because EF Core DbContext are expected to be scoped and generally short lived we recommend using them with OwningComponentBase so that data doesn’t accumulate unnecessarily in the DbContext instance. Using OwningComponentBase will cause the DbContext to have the same lifetime as the component. If you don’t use OwningComponentBase, then the DbContext will live for the life of the connection, which may be problematic if your clients stay connected for a long time.

    • Daniel Roth
      Daniel Roth

      In a Blazor Server app you can use `@(await Html.RenderStaticComponentAsync<App>(RenderMode.Server)) to avoid prerendering. Blazor Server apps no longer use the older CSS selector mechanism.

      • Avatar
        Mark Stega

        That’s what I thought, but my experience is that with the mode of ServerPreRendered my application starts and is not functional (The first screen appears but no interaction is possible). When I switch the mode to Server i get as far as seeing the placeholder in the html (using the developer tools in FF) but the application never renders. What I see ‘on screen’ is a blank browser window. What I see in the html is
        “`
        <!–Blazor:{“sequence”:0,”type”:”server”,”descriptor”:”CfDJ8BPjNbRN-zZEiUFkxU35S5GqKJr8jHGalphX0J_ugdc8BYHk-h8qdhMUl7_GD-UXirIQQ5vwebuf4fIB3Cm1JSxT8v3c1YP1NcOMxVOIO5GDQQrjIz_Gn0g8YK0bWcgf8KU-D66Rp6WaSDa-8AOwPtdAGTXFxhp6w8wmWSpx07kssuq_ccShd-YLMIjNBpHdxSST1vz-G65F1wMmWQBrQWMv7m7OcW_ojx4UoX8IcXH9-YAq3Z6lLGk11oS3T5ILsxPDpsdvxNKw41DdxwEI3xP_SMVqjhAeAPB86ayYiGNoG6T7PrpCmhQlEifTtbzOfw”}–>
        “`
        The same app launched client-side work with no issue.
        Any thoughts on what I might be doing wrong in the app?
        BTW, this new method removes a use case that I was employing that had html/css in between the <app></app> to show a spinner until the content loaded. That still works with a wasm client but no longer with server side rendering. On the bright side, the startup is so much faster there is little meed for the spinner if server side.

        • Avatar
          Mark Stega

          Additional info — Wth ServerPreRendered the html has the placeholders and they are never replaced with active content. When I switch my app to client side wasm execution everything works. The app is embodied in a couple of Razor Class Libraries so my switch is simply changing the DNC startup.cs file (which I do with a configuration switch)  to go between CSE/SSE.

          • Avatar
            Mark Stega

            No errors in the dev tools nor the server logs. I have a small repository that demonstrates the problem so I’ll open an issue and reference it there. On the server side I don’t feel the need for the spinner as startup is so fast. On the client I’d like it to be preserved.

  • Avatar
    Brown, Stephen

    I have upgraded a Blazor Web Assembly project from preview 7 to preview 9. Updated VS 2-19, installed new project templates and followed instructions above for Router, etc. After resolving all of the errors, I attempt to build the project from VS and get the following msbuild error:
    error MSB3073: The command “dotnet ….<build dependencies, etc> ….   exited with code -532462766
    Any ideas what is wrong, I have the latest .NET COre 3 preview installed which appears to have been done with the VS update.
    Thanks

    • Daniel Roth
      Daniel Roth

      Do you see any additional errors in the build output in the output tab in Visual  Studio? What about when building the project on the command line using `dotnet build`? 

      • Avatar
        Stephen Brown

        Hi Daniel, yes dotnet build does fail with the same error. Just noticed from VS outout that I also have this:
        Unhandled Exception: Mono.Cecil.ResolutionException: Failed to resolve Microsoft.AspNetCore.Components.IComponentContextat Mono.Linker.Steps.MarkStep.HandleUnresolvedType(TypeReference reference)at Mono.Linker.Steps.MarkStep.MarkType(TypeReference reference)at Mono.Linker.Steps.MarkStep.MarkField(FieldReference reference)at Mono.Linker.Steps.MarkStep.InitializeFields(TypeDefinition type)at Mono.Linker.Steps.MarkStep.InitializeType(TypeDefinition type)at Mono.Linker.Steps.MarkStep.InitializeAssembly(AssemblyDefinition assembly)at Mono.Linker.Steps.MarkStep.Initialize()at Mono.Linker.Steps.MarkStep.Process(LinkContext context)at Mono.Linker.Pipeline.ProcessStep(LinkContext context, IStep step)at Mono.Linker.Pipeline.Process(LinkContext context)at Mono.Linker.Driver.Run(ILogger customLogger)at Mono.Linker.Driver.Execute(String[] args, ILogger customLogger)at Mono.Linker.Driver.Main(String[] args)

        • Daniel Roth
          Daniel Roth

          Looks like you’re still using IComponentContext somewhere in your app. This service was removed in this release. Instead, we now guarantee that OnAfterRender and OnAfterRenderAsync are not called during prerendering.

  • Rafael Dominguez
    Rafael Dominguez

    I’m upgrading to Prev.9 it’s going ok but I can’t seem to find the replacement for keyboard events. Changing UIKeyboardEventArgs to KeyboardEventArgs still gives an error and so does KeyPressEventArgs. What’s the path to take here? Thanks

      • Ian Sharp
        Ian Sharp

        I have Microsoft.AspNetCore.Components.Web and Microsoft.AspNetCore installed and still get the error

        Error CS0246: The type or namespace name ‘KeyboardEventArgs’ could not be found (are you missing a using directive or an assembly reference?) (CS0246)

        dotnet –info
        .NET Core SDK (reflecting any global.json):
        Version: 3.0.100-preview9-014004
        Commit: 8e7ef240a5

        Runtime Environment:
        OS Name: Mac OS X
        OS Version: 10.14
        OS Platform: Darwin
        RID: osx.10.14-x64
        Base Path: /usr/local/share/dotnet/sdk/3.0.100-preview9-014004/

        Host (useful for support):
        Version: 3.0.0-preview9-19423-09
        Commit: 2be172345a

        .NET Core SDKs installed:
        3.0.100-preview9-014004 [/usr/local/share/dotnet/sdk]

        .NET Core runtimes installed:
        Microsoft.AspNetCore.App 3.0.0-preview9.19424.4 [/usr/local/share/dotnet/shared/Microsoft.AspNetCore.App]
        Microsoft.NETCore.App 3.0.0-preview9-19423-09 [/usr/local/share/dotnet/shared/Microsoft.NETCore.App]

        dotnet –info
        .NET Core SDK (reflecting any global.json):
        Version: 3.0.100-preview9-014004
        Commit: 8e7ef240a5

        Runtime Environment:
        OS Name: Mac OS X
        OS Version: 10.14
        OS Platform: Darwin
        RID: osx.10.14-x64
        Base Path: /usr/local/share/dotnet/sdk/3.0.100-preview9-014004/

        Host (useful for support):
        Version: 3.0.0-preview9-19423-09
        Commit: 2be172345a

        .NET Core SDKs installed:
        3.0.100-preview9-014004 [/usr/local/share/dotnet/sdk]

        .NET Core runtimes installed:
        Microsoft.AspNetCore.App 3.0.0-preview9.19424.4 [/usr/local/share/dotnet/shared/Microsoft.AspNetCore.App]
        Microsoft.NETCore.App 3.0.0-preview9-19423-09 [/usr/local/share/dotnet/shared/Microsoft.NETCore.App]

        • Ian Sharp
          Ian Sharp

          woops, I had a second _Imports.razor that needed

          @using Microsoft.AspNetCore.Components.Web
          @using Microsoft.AspNetCore.Components.Authorization

          Now I no longer get the error Error CS0246: The type or namespace name ‘KeyboardEventArgs’ could not be found

  • Avatar
    Ronald Wingelaar

    Hi Daniel,
    I have problems after this update with tablets, both android and iOS. I have made a new project from the template, for this test clientside only. ON my desktop it’s working fine but on tablets it keeps loading…..
    You can check it yourself on this url: slimtab.innovixion.nl

    • Daniel Roth
      Daniel Roth

      I tried accessing the website on my desktop and Android phone (yes, I do sometimes click on random links on the internet :oP) and I get the same experience where the website loads but I get an authorization error. Is it possible you hit some sort of network issue on your tablets? Do you have any firewall/proxy on your network that might be blocking the .dll files from being downloaded? If you think this is a bug in Blazor, please go ahead and file on issue at https://github.com/aspnet/aspnetcore/issues with full details of your setup and we’ll take a look.

  • Avatar
    Jai Misra

    I started as a pure version 3.0 Blazor application (with _hosts.cshtml and .razor files)… then I added the identity scaffolding which created a bunch of cshtml files along with _layout.html and I had to figure out the interplay between the _hosts.cshtml and _layout.cshtml. After a few rounds of trial and error I moved everything from the _hosts.html except for the <app>@(await Html.RenderComponentAsync<App>())</app> and it was working fine till preview 9. Now in preview 9 i have to change it to <app>@(await Html.RenderComponentAsync<App>(RenderMode.Server))</app> and that’s when the hell breaks loose :-). I.e. nothing gets rendered on the UI.
    Has anyone else tried something similar? The basic question here is how does one do identity scaffolding with Blazor 3.0 application the right way. If I move the line <app>@(await Html.RenderComponentAsync<App>(RenderMode.Server))</app> to _Layout.cshtml then it works but then the index.razor page gets rendered along with any .cshtml file of scaffolded identity.
    Also, an observation if I use the render mode as ServerPreRendered and leave that line on the _hosts.cshtml then the blazor UI does show up but without any interactivity (i.e. no events firing etc.).
    Thanks.

  • Avatar
    Serge Racine

    ASP.NET Core and Blazor updates in .NET Core 3.0 Preview 9.19424.4
    How resolve the error CS1503 Argument 2 : conversion impossible de ‘groupe de méthodes’ en ‘EventCallback for:DoStuffP
    It was ok with Preview 8        <select @onchange=DoStuffP>            @foreach (var templateP in templatesP)            {                <option value=@templateP>@templateP</option>            }        </select>        <p>Your choice is: @habiletéP</p>        @code {            List<string> templatesP = new List<string>() {        “Faites votre choix”,        “HABILETÉ 1”,        “HABILETÉ 2”,        “HABILETÉ 3”,        “HABILETÉ 4” };            string habiletéP = “Faites votre choix”;            void DoStuffP(Microsoft.AspNetCore.Components.Web.ChangeEventArgs e)            {                habiletéP = e.Value.ToString();            }        }

  • Hienadź Budkoŭski
    Hienadź Budkoŭski

    Hey, everyone, hey Daniel! i just moved to preview 9 and got some unexpected error. Blazor just lost connection between server and client side. https://ibb.co/27Ys3GF
    I reread the whole article, mb i missed update javascript client code, or something in version. Please can some explain what’s happening. It’s can’t call method ‘StartCircuit’

    • Daniel Roth
      Daniel Roth

      I haven’t seen this error before. Is the blazor.server.js file being used perhaps out of sync with the server? Maybe try clearing the browser cache? Also check your project file to enusre you have a consistent set of dependency versions. If you think you might have hit a bug, please open an issue on https://github.com/aspnet/aspnetcore/issues with details on how to reproduce the issue and we’ll investigate.

      • Hienadź Budkoŭski
        Hienadź Budkoŭski

        Thx for reply, i fixed it – had to delete all nuget packages and caches and finally bingo. i think it was usign wrong cached version of dll library. in any strange situation delete nuget packages=)
        Added later *for those who google it error was ‘failed to start a circuit doe to error on server’ 

  • Avatar
    Mark Shortt

    Hi
    I had been using Microsoft.AspNetCore.Blazor.Services.WebAssemblyUriHelper to get the base URI, but with Preview 9 the Microsoft.AspNetCore.Blazor.Services doesn’t appear to be present
    What’s the correct way to to get the base Uri in a Web Assembly app? 

    Thanks

  • Frédéric Taillefer
    Frédéric Taillefer

    Really enjoying blazor lately. Does this version has a json serializer that knows how to deserialize to class with no parameterless contructor (like KeyValuePair for instance ?). If not, will it be fixed in the final version ? tks

  • Avatar
    Charles Rouhier

    Right off the bat … I’m new to Blazor and just learning it.  So far, I like what I see and think it will offer some big benefits for a number of projects we need to convert from Flash.  So with that, I’ve been trying to get the Blazor events to work now for a couple of weeks without success.  I just upgraded to Preview9 and they still don’t work (Yes.  VS Preview 3.0).  I went back to the basics.  A Blazor WebServer app created from the template.  Made sure everything referenced in _Import.razor was installed from NuGet and still the Counter onclick event will not fire.  What am I missing?

    • Daniel Roth
      Daniel Roth

      Hi Charles,

      I’m sorry to hear you’re having issues! Could you please check the brower console and and the server logs to see if there are any errors that show up there when you click the Counter button?

      Thanks for taking the time to learn Blazor! Hopefully we’ll get you sorted out soon.

      • Avatar
        Charles Rouhier

        The Windows Logs/Application event log shows the following warning when the debug session starts up in VS:The directory specified for caching compressed content C:\inetpub\temp\IIS Temporary Compressed Files\BlazorServerTestApp AppPool is invalid. Static compression is being disabled.I don’t see any errors in the event logs or browser console when I press the ‘Click Me’ button.  Someplace else you want me to look?
        I see one error in the browser console when I click on the Counter menu item: CSS3111:@font-face encountered unknow error.open-iconic.eot
        Also, I see this line in the debugger <script src=”_framework/blazor.server.js”></script>.  However, no such folder was created when from the template .

      • Avatar
        Charles Rouhier

        Daniel,  I believe I’ve found the issue.  It appears Blazor doesn’t like IE.  I found a statemen on this page indicating you could only debug in Chrome or Edge. https://docs.microsoft.com/en-us/aspnet/core/blazor/debug?view=aspnetcore-3.0I switched to Edge and now they work.  I’ve been trying to get EventCallback’s to work too, which led me going back to the basics, hopefully this solves the issues I’ve been having with the callback’s.BTW, I don’t know if you’re aware, but the tree for the Blazor doc’s doesn’t render in Edge for some reason.  It does in IE.
        Thanks for the help.
        Chuck

        • Daniel Roth
          Daniel Roth

          Yeah, Blazor Server apps can be made to work in IE, but you need to add the appropriate polyfills yourself. Checkout https://github.com/Daddoon/Blazor.Polyfill for a community based solution. Blazor WebAssembly apps are not supported at all in IE, because IE doesn’t support WebAssembly.

          Thanks for bringing the Blazor docs issue to our attention! Unfortunately, I’m not able to reproduce this. The docs seem fine in both Edge and Edge (dev) as far as I can tell. Could you please open an issue in https://github.com/aspnet/aspnetcore.docs/issues with a screen shot of what you are seeing? Thanks again!

          • Avatar
            Charles Rouhier

            Thanks for the link.
            The Edge thing probably has something to do with where I work.  We have issues with other things in Edge, too.  So, I’ll just chalk it up to that for now.
            Thanks again for the assist.
            Chuck

  • Rajni Kumar
    Rajni Kumar

    After upgrading to preview 9 my ApiAuthenticationStateProvider class does not compile. I get error “no suitable method to override on GetAuthenticationStateAsync and NotifyAuthenticationStateChanged. I have installed package Microsoft.AspNetCore.Components.Authorization3.0.0-preview9.19424.4. Is there anything i am missing?

      • Rajni Kumar
        Rajni Kumar

        It is asp.net core hosted webassembly project. I have using statement Microsoft.AspNetCore.Components.Authorization but it turns gray

        • Avatar
          marouen kharraz

          I think you need to add “using Microsoft.AspNetCore.Components.Authorization” in the .cs file too and that would correct it.

  • Avatar
    Darrell Tunnell

    Nothing mentioned about this breaking change:
    In a .razor file, if you used a generic component with a type argument it used to be <MyComonent T=”SomeType” /> but that will now error out. You have to change it to <MyComonent TValue=”SomeType” />

  • Riaan G
    Riaan G

    Seems that NavigationManager has “BaseUri” instead of “GetBaseUri()”If you’re using :Blazored.LocalStorageBlazored.SessionStorage
    Just upgrade to the latest versions. The change Task<> to ValueTask<> has been updated I believe.Prev 8 to 9 was by far the easiest upgrade for me.Back to having fun!

  • Avatar
    Maciej Misztal

    @Daniel I may have missed this, but is the “Microsoft.AspNetCore” not a part of the ASP.NET Core 3.0? Latest published version is 2.2.0 ?

  • Felipe Almeida
    Felipe Almeida

    Hey, just installed the latest version of vs along of the web assembly preview and created a webassembly project but the compiler does not found “mapFallbackToClientSideBlazor, along with other functions. Any help?

Leave a comment