Posted on Leave a comment

Announcing ASP.NET Core in .NET 5

Daniel Roth

Daniel

.NET 5 is now released! .NET 5 is the next version of .NET Core and the future of the .NET platform. With .NET 5 you have everything you need to build rich, interactive front end web UI and powerful backend services.

ASP.NET Core in .NET 5 is loaded with lots of great new features and improvements. Here’s a sampling:

For a full list of everything that’s new in ASP.NET Core in this release, check out the ASP.NET Core in .NET 5 release notes. See also the .NET 5 release notes for additional details and known issues.

Get started

To get started with ASP.NET Core in .NET 5, install the .NET 5 SDK. .NET 5 is also included with the latest updates to Visual Studio and Visual Studio for Mac, so if you’ve already updated your IDE, then you should be good to go.

Visual Studio 2019 16.8 or later is required to use .NET 5 from Visual Studio. .NET 5 is also supported with Visual Studio for Mac. To use .NET 5 with Visual Studio Code, install the latest version of the C# extension.

Upgrade an existing project

To upgrade an existing ASP.NET Core app from .NET Core 3.1 to .NET 5:

To upgrade an existing ASP.NET Core app from .NET 5 RC2 to .NET 5:

  • Update all Microsoft.AspNetCore.*, Microsoft.Extensions.*, and System.* package references to 5.0.0.

That’s it! You should be all set to enjoy the benefits of .NET 5.

See also the full list of breaking changes in ASP.NET Core for .NET 5.

Performance improvements

With every .NET release a special effort is made to improve all aspects of the performance in ASP.NET Core applications. ASP.NET Core in .NET 5 is the fastest .NET web framework we’ve ever shipped!

.NET 5 contains great performance improvements in the runtime and libraries and for the gRPC components. These improvements, when applied to ASP.NET Core, result in some significant wins in throughput (RPS) and latency. The performance results below are taken from the TechEmpower benchmarks for ASP.NET Core with .NET Core 3.1 and from the latest results for ASP.NET Core with .NET 5.

Troughput (max, in RPS)

Scenario 3.1 5.0 Change
Plaintext Platform 8,593 11,690 +36.0%
Json Platform 872 1,261 +44.6%
Fortunes Platform 344 423 +23.0%
Plaintext 3,993 4,420 +12.4%
Json 743 912 +22.6%
Fortunes 223 259 +16.2%

Latency (mean, in ms)

Scenario 3.1 5.0 Change
Plaintext Platform 1.52 0.82 -46.3%
Json Platform 1.24 0.41 -66.7%
Fortunes Platform 1.57 1.26 -19.7
Plaintext 0.87 0.83 -4.2%
Json 1.52 1.20 -21.1%
Fortunes 1.11 0.87 -21.6

The “platform” tests represent highly optimized benchmark implementations, while the non-platform tests use more typical framework components.

The TechEmpower performance composite score, an index based on all of the TechEmpower benchmarks aggregated together, increased from 5,659 to 6,626 with .NET 5, which represents a 17% increase.

Deploy .NET 5 Web Apps to Azure App Service Today

The ASP.NET and Azure App Service teams have worked tirelessly together throughout the .NET 5 timeline to make sure ASP.NET developers have access to the latest bits of the .NET 5 runtime on day zero. This means that, as soon as you can download .NET 5 and get started building apps with it, you can deploy those .NET 5 apps to App Service using Visual Studio and Visual Studio Code, and you’ll have full support for deploying .NET 5 apps to App Service using GitHub Actions.

This day-zero availability of .NET 5 on App Service will be made possible by their new Early Access Runtime feature, which will enable not only .NET 5 apps, but every subsequent release of .NET from now on. This means no more waiting for the platform to support the runtime – it’ll “just be there” as soon as the runtime is available. You can learn more about the Azure App Service Early Access Runtime technology on the App Service team’s blog.

Whilst Early Access will give you a supported path to deploying your .NET 5 apps to Azure App Service immediately, there are some slight nuances to how Early Access works with which you can familiarize yourself on the App Service Early Access .NET page.

Join us for the .NET 5 release at .NET Conf 2020

Come celebrate with us and learn all about the .NET 5 release at .NET Conf 2020, a FREE, three day virtual developer event co-organized by the .NET community and Microsoft. This year marks the 10th anniversary of the conference, and it will be better than ever with over 80 live sessions from speakers in the community and from the Microsoft product teams. The conference starts today and goes from November 10-12. We hope you can join us!

Thank you!

Thank you to everyone in the community who helped make this release of .NET 5 possible! This release represents the culmination of many GitHub issues, pull requests, design feedback comments and documentation updates contributed by many members of the .NET community. We couldn’t have made it to this point without you!

We hope you enjoy this release of ASP.NET Core in .NET 5. We are eager to hear about your experiences with this latest release. Let us know what you think on GitHub by filing new issues and by commenting on or expressing your support (👍) for existing ones.

Thanks again for trying out ASP.NET Core!

Posted on Leave a comment

Unified Blazor UI in the Mobile Blazor Bindings Preview 5

Eilon Lipton

Eilon

I’m excited to announce that today we are releasing the Mobile Blazor Bindings Preview 5 update that adds support for sharing UI between web apps and mobile/desktop apps. You can now use a Razor Class Library (RCL) to build your UI and app logic once and use it in a Blazor Web app and in a Mobile Blazor Bindings app. This release also includes many other improvements, such as support for Shell with Blazor @page routing, SkiaSharp for rich graphics, gesture recognizers, and a whole lot more!

You can build one UI using Blazor Web and host it in a Blazor Server or Blazor Web Assembly app and also in a Mobile Blazor Bindings hybrid app to target Android, iOS, macOS, and Windows:

Image cat tracker options

These are the major new features in the 0.5 Preview 5 release:

  • Build your UI in a Razor Class Library (RCL) and share the same UI between web app and native app, including static assets such as CSS and images (community contribution from Jan-Willem Spuij)
  • Support for Shell with Routing, including the Razor @page directive (community contribution from Lachlan Gordon
  • Support for SkiaSharp graphics (community contribution from Lachlan Gordon
  • Gesture recognizers (tap, swipe, etc.)
  • Dual-screen device support
  • Added FontImageSource, DatePicker, TimePicker
  • Simplified Grid layout syntax
  • Update to Xamarin.Forms 4.8
  • Nightly package feed
  • OSS docs on GitHub
  • And several bug fixes and other small improvements
  • The full list of closed issues is here: https://github.com/xamarin/MobileBlazorBindings/milestone/5?closed=1

Get started

To get started building a Blazor Hybrid app with Experimental Mobile Blazor Bindings preview 5, install the .NET Core 3.1 SDK, have Visual Studio with the Mobile development with .NET (Xamarin.Forms) and ASP.NET and web development workloads installed, and then run the following command:

dotnet new -i Microsoft.MobileBlazorBindings.Templates::0.5.50-preview

And then create your first project by running this command:

dotnet new blazorhybrid -o MyHybridApp

Note: For additional information on required software, please check the Getting Started article.

Now open it in Visual Studio and run it on Android, iOS, Windows, or macOS. That’s it! You can find additional docs and tutorials on https://docs.microsoft.com/mobile-blazor-bindings/. We have a new tutorial for building a Razor Class Library and including it in a Blazor Server app as well as targeting Android, iOS, macOS, and Windows platforms.

Upgrade an existing project

To update an existing Mobile Blazor Bindings project please refer to the Migrate Mobile Blazor Bindings From Preview 4 to Preview 5 topic for full details.

Razor Class Library support

Razor Class Libraries are a feature of Razor that enable you to package part of your application’s UI and logic into a reusable library. This library can then be reused in multiple web applications. Now in Mobile Blazor Bindings you can use the same library in a Blazor Hybrid application as part of a mobile or desktop app. The web content is hosted in a Web View, just like any hybrid app content, and it can interact with any native parts of the application, and the reverse is true as well. Previous versions included limited support for RCLs, and this version adds improved support for them, particularly support for serving static assets such as CSS and images, as well as support for JSInterop for interop between JavaScript and .NET code.

Shell navigation

To build a great native experience for your app you can use the Shell control that comes from Xamarin.Forms. Starting with Preview 5 you can author native Blazor pages with the @page "/search/{query}" syntax and integrate them with the Shell’s navigation (such as the Back button) and navigate to them using the new NavigationManager.NavigateToAsync($"/search/{query}") API. Pages can use the navigation manager by injecting it from the DI container as in @inject ShellNavigationManager NavigationManager.

SkiaSharp graphics

SkiaSharp is a popular cross-platform graphics library based on Google’s Skia graphics library. In Preview 5 you can directly use SkiaSharp’s Canvas APIs to render rich high-performance graphics directly in your Mobile Blazor Bindings app.

Here’s what a simple canvas might look like:

<ContentView> <StackLayout Padding="20"> <SKCanvasView OnPaintSurface="PaintSurface"/> </StackLayout>
</ContentView> @code
{ void PaintSurface(SKPaintSurfaceEventArgs e) { var canvas = e.Surface.Canvas; canvas.Clear(SKColors.Green); var paint = new SKPaint { Color = SKColors.SkyBlue, }; canvas.DrawLine(0, 0, 200, 200, paint); }
}

And here’s what a more complex canvas might render as:

SkiaSharp rendering a graph in Mobile Blazor Bindings on iOS

More information

Thank you to contributors

This release had several major contributions from community contributors:

  • Jan-Willem Spuij added support for Razor Class Libraries with static assets. He stayed up late (his time) on calls with me several times and I appreciate his hard work!
  • Lachlan Gordon added support for Shell navigation and SkiaSharp. His patience in playing time-zone ping-pong (Australia vs. USA) is most appreciated and resulted in high quality contributions!

Thanks you to Jan-Willem, Lachlan, and everyone else who contributed to this release!

What’s next? Let us know what you want!

This project relies on your feedback to help shape the future of Blazor for native and hybrid scenarios. Please share your thoughts on this blog post or at the GitHub repo so we can keep the discussion going.

Posted on Leave a comment

ASP.NET Core updates in .NET 5 Release Candidate 2

Daniel Roth

Daniel

.NET 5 Release Candidate 2 (RC2) is now available and is ready for evaluation. .NET 5 RC2 is a “go live” release, meaning it’s supported in production. This prerelease of .NET 5 is very close to what we expect to ship for the .NET 5 release.

Here’s what’s new in this RC2 release:

  • CSS isolation improvements
  • Blazor WebAssembly debugging improvements
  • Browser platform compatibility tooling

ASP.NET Core in .NET 5 contains lots of great new functionality and improvements! The list below summarizes the many improvements we’ve made in ASP.NET Core for .NET 5 that you can try out in this release:

See the .NET 5 release notes for additional details and known issues.

Get started

To get started with ASP.NET Core in .NET 5 RC2, install the .NET 5 SDK. .NET RC2 also is included with Visual Studio 2019 16.8 Preview 4.

Visual Studio 2019 16.8 Preview 4 or later is required to use .NET 5 RC2 from Visual Studio. .NET 5 RC2 is also supported with the latest preview of Visual Studio for Mac. To use .NET 5 with Visual Studio Code, install the latest version of the C# extension.

Upgrade an existing project

To upgrade an existing ASP.NET Core app from .NET 5 RC1 to .NET 5 RC2:

  • Update all Microsoft.AspNetCore.* package references to 5.0.0-rc.2.*.
  • Update all Microsoft.Extensions.* package references to 5.0.0-rc.2.*.
  • Update System.Net.Http.Json package references to 5.0.0-rc.2.*.
  • Update Microsoft.AspNetCore.Components.Web.Extensions package references to 5.0.0-preview9.20513.1.
  • Remove any package references to Microsoft.AspNetCore.Components.ProtectedBrowserStorage
  • Update Microsoft.AspNetCore.Components.ProtectedBrowserStorage namespace to Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage.
  • Remove unnecessary service registrations for ProtectedLocalStorage and ProtectedSessionStorage.
  • Rename JSObjectReference to IJSObjectReference.
  • In Blazor apps, replace CSS references to _framework/scoped.styles.css and _content/{project_name}/_framework/scoped.styles.css with {project_name}.styles.css.

That’s it! You should be all ready to go.

See also the full list of breaking changes in ASP.NET Core for .NET 5.

What’s new?

Blazor CSS isolation improvements

In .NET 5 Preview 8 we introduced support for CSS isolation for Blazor components. Based on user feedback, we’ve made a number of improvements to CSS isolation in this release.

Previously, all component scoped CSS files including files from referenced projects or packages were compiled into a single bundle, scoped.styles.css. We now produce one bundle per referenced project or package and include those bundles into the app bundle through CSS @import statements.

The bundle names are now based on the project names: {project_name}.styles.css. Each bundle can be referenced from the root path of the app by default. This makes the path of the app bundle the same for both Blazor Server and Blazor WebAssembly projects:

<link href="BlazorApp1.styles.css" rel="stylesheet" />

Component specific styles can also now use normal wwwroot-relative paths to refer to related assets, like images. We’ve updated Razor Class Library template to make use of component specific styles following this pattern.

Component1.razor.css

.my-component { border: 2px dashed red; padding: 1em; margin: 1em 0; background-image: url('background.png');
}

We also fixed some issues with how scoped CSS styles get built so that changes are correctly picked up with each build in Visual Studio instead of requiring a full rebuild.

Blazor WebAssembly debugging improvements

.NET 5 includes a variety of improvements to Blazor WebAssembly debugging:

  • Various reliability improvements, including fixing the port conflict issue from RC1
  • Improved support for stepping over and out of async methods
  • Inspect locals or object properties in many previously unsupported situations:
    • For inherited members
    • For multicast delegates
    • For boxed values
    • For Nullable<T> values
    • Within reflection based calls
  • Support for debugging lazy loaded assemblies

Browser platform compatibility tooling

The core framework libraries in .NET 5 have now been annotated to indicate which APIs are supported in browser scenarios. The platform compatibility analyzer uses this data to give appropriate warnings when using APIs from a Blazor WebAssembly app that are not supported when running in a browser on WebAssembly.

Browser compatibility check

Learn more about how you can use the new platform compatibility analyzer to discover cross-platform compatibility issues.

Give feedback

We hope you enjoy this release of ASP.NET Core in .NET 5! We are eager to hear about your experiences with this latest .NET 5 release. Let us know what you think by filing issues on GitHub.

Thanks for trying out ASP.NET Core!

Posted on Leave a comment

Azure Static Web Apps with .NET and Blazor

aapowell

Aaron

Azure Static Web Apps is a service that automatically builds and deploys full stack web apps from a GitHub repository. Azure Static Web Apps consist of a static web frontend, and an Azure Functions based backend. When you create a Static Web Apps resource, Azure sets up a GitHub Actions workflow in the app’s source code repository that monitors a branch of your choice. Every time you push commits to the watched branch, the GitHub Action automatically builds and deploys your app and its API.

As of today, Azure Static Web Apps now has first-class support for Blazor WebAssembly and .NET Functions in preview, available in all supported regions. This was one of the top user requests since Static Web Apps was announced at Build. You can develop and deploy a frontend and a serverless API written entirely in .NET.

Let’s give it a try!

Getting Started

To help you get started, we’ve created a GitHub repository template, which you can use as a starting point for your own projects.

In GitHub, click on the Use this template button to create a new GitHub repository using the template, providing it a name of your choosing (we’ll use my-blazor-app here) and click Create repository from template.

There are three folders in the template:

  • Client: The Blazor WebAssembly sample application
  • API: A C# Azure Functions API, which the Blazor application will call
  • Shared: A C# class library with a shared data model between the Blazor and Functions application

To run the app locally, start both the API and Client projects. The “Fetch data” page in the Blazor app requests weather forecast data form the backend Function API and display it on the page.

To run the app from the command-line, you’ll need to install the Azure Functions Core Tools for your platform of choice.

Deploying to Static Web Apps

To deploy this app as an Azure Static Web App, log into your Azure account (sign up for a free one here) and search for Static Web Apps.

Static Web Apps in the portal

Click Create, provide a Subscription, Resource Group and name for the application.

Next, sign into GitHub and locate your GitHub repo (my-blazor-app) and select the branch you wish to deploy.

Finally, select Blazor from the Build Presets, which will populate the App location, API location and App artifact location with Client, API and wwwroot. The first and second values are the path within the Git repository to where the project files for the Blazor and Functions app resides, so if you’ve modified the structure of the Git repository, make sure these values are updated to reflect. The third value is the output path that Blazor will compile into and doesn’t need updating.

Azure Static Web App wizard

Complete the wizard and Static Web Apps will create the GitHub Actions workflow file for you and deploy your application to Azure.

gif of Action completing and then going to the portal to open the deployed app

Summary

We started by forking a GitHub repository (but you could’ve also used a project created in Visual Studio/Visual Studio Code/etc.), created a Static Web App in Azure, and it setup a GitHub Actions workflow for us, automatically building and deploying our Blazor and Functions application. We’ve now got a statically hosted application with a serverless backend, ready to scale for our demands.

Additional Resources

To learn more about Blazor WebAssembly and .NET Functions on Static Web Apps, check out the quickstart docs, the Microsoft Learn module, as well as the comprehensive Static Web Apps docs.

Give Feedback

We’re excited to have Blazor WebAssembly and .NET Functions supported by Azure Static Web Apps, and can’t wait to see what you build with them. Let us know what you think by filing an issue on GitHub.

Posted on Leave a comment

Free e-book: Blazor for ASP.NET Web Forms Developers

Avatar

Nish

We are thrilled to announce the release of our new e-book: Blazor for ASP.NET Web Forms developers. This book caters specifically to ASP.NET Web Forms developers looking for guidelines. As well as strategies for migrating their existing apps to a modern, open-source, and cross-platform web framework.

Blazor E-book for ASP.NET Web Forms

Blazor is a new web framework that changes what is possible when building web apps with .NET. It is also a client-side web UI framework based on C# instead of JavaScript. When paired with .NET running on the server, Blazor enables full-stack web development with .NET. Blazor shares many commonalities with ASP.NET Web Forms. Such as having a reusable component model and a simple way to handle user events. It also builds on the foundations of .NET Core to provide a modern and high-performance web development experience. Additionally, Blazor is a natural solution for ASP.NET Web Forms developers looking to take advantage of client-side development and the open-source, cross-platform future of .NET.

In this book, each Blazor concept is presented in the context of analogous ASP.NET Web Forms features and practices. The book covers:

  • Building Blazor apps.
  • How Blazor works.
  • Blazor’s relation to .NET Core.
  • Reasonable strategies for migrating existing ASP.NET Web Forms apps to Blazor where appropriate.
  • A reference sample that demonstrates the migration strategies used.

Blazor for ASP.NET Web Forms Developers Cover Image
Read Online

Should I Still Use ASP.NET Web Forms?

Of course! As long as the .NET Framework ships as part of Windows, ASP.NET Web Forms will be supported. For many Web Forms developers, the lack of cross-platform and open-source support is a non-issue. If you do not require cross-platform support, open-source, or any other new features in .NET Core or .NET 5, then stick with ASP.NET Web Forms on Windows. ASP.NET Web Forms will continue to be a productive way to write web apps for many years to come!

Other Free E-books

If you are in the path of migrating your existing web and server apps, check out our free e-books on gRPC for WCF Developers. As well as Migrating your .NET App to Azure and more at dot.net/architecture.

Feedback

The book and related reference application will be evolving, so we welcome your feedback! If you have comments about how this book can be improved, please submit feedback.

Posted on Leave a comment

ASP.NET Core updates in .NET 5 Preview 8

Daniel Roth

Daniel

.NET 5 Preview 8 is now available and is ready for evaluation. Here’s what’s new in this release:

  • Azure Active Directory authentication with Microsoft.Identity.Web
  • CSS isolation for Blazor components
  • Lazy loading in Blazor WebAssembly
  • Updated Blazor WebAssembly globalization support
  • New InputRadio Blazor component
  • Set UI focus in Blazor apps
  • Influencing the HTML head in Blazor apps
  • IAsyncDisposable for Blazor components
  • Control Blazor component instantiation
  • Protected browser storage
  • Model binding and validation with C# 9 record types
  • Improvements to DynamicRouteValueTransformer
  • Auto refresh with dotnet watch
  • Console Logger Formatter
  • JSON Console Logger

See the .NET 5 release notes for additional details and known issues.

Get started

To get started with ASP.NET Core in .NET 5 Preview 8 install the .NET 5 SDK.

You need to use Visual Studio 2019 16.8 Preview 2 or newer to use .NET 5 Preview 8. .NET 5 is also supported with the latest preview of Visual Studio for Mac. To use .NET 5 with Visual Studio Code, install the latest version of the C# extension.

Upgrade an existing project

To upgrade an existing ASP.NET Core app from .NET 5 Preview 7 to .NET 5 Preview 8:

  • Update all Microsoft.AspNetCore.* package references to 5.0.0-preview.8.*.
  • Update all Microsoft.Extensions.* package references to 5.0.0-preview.8.*.
  • Update System.Net.Http.Json package references to 5.0.0-preview.8.*.

That’s it! You should be all ready to go.

See also the full list of breaking changes in ASP.NET Core for .NET 5.

What’s new?

Azure Active Directory authentication with Microsoft.Identity.Web

The ASP.NET Core project templates now integrate with Microsoft.Identity.Web to handle authentication with Azure Activity Directory (Azure AD). The Microsoft.Identity.Web package provides a better experience for authentication through Azure AD as well as an easier way to access Azure resources on behalf of your users, including Microsoft Graph. Check out the Microsoft.Identity.Web sample that take you from a simple login through multi-tenancy, using Azure APIs, using Microsoft Graph, and protecting your own APIs. Microsoft.Identity.Web will be generally available alongside .NET 5.

CSS isolation for Blazor components

Blazor now supports defining CSS styles that are scoped to a given component. Component specific CSS styles make it easier to reason about the styles in your app and to avoid unintentional side effects from global styles. You define component specific styles in a .razor.css file the matches the name of the .razor file for the component.

For example, let’s say you have a component MyComponent.razor file that looks like this:

MyComponent.razor

<h1>My Component</h1> <ul class="cool-list"> <li>Item1</li> <li>Item2</li>
</ul>

You can then define a MyComponent.razor.css with the styles for MyComponent:

MyComponent.razor.css

h1 { font-family: 'Comic Sans MS'
} .cool-list li { color: red;
}

The styles in MyComponent.razor.css will only get applied to the rendered output of MyComponent; the h1 elements rendered by other components, for example, are not affected.

To write a selector in component specific styles that affects child components, use the ::deep combinator.

.parent ::deep .child { color: red;
}

By using the ::deep combinator, only the .parent class selector is scoped to the component; the .child class selector is not scoped, and will match content from child components.

Blazor achieves CSS isolation by rewriting the CSS selectors as part of the build so that they only match markup rendered by the component. Blazor then bundles together the rewritten CSS files and makes the bundle available to the app as a static web asset at the path _framework/scoped.styles.css.

While Blazor doesn’t natively support CSS preprocessors like Sass or Less, you can still use CSS preprocessors to generate component specific styles before they are rewritten as part of the building the project.

Lazy loading in Blazor WebAssembly

Lazy loading enables you to improve the load time of your Blazor WebAssembly app by deferring the download of specific app dependencies until they are required. Lazy loading may be helpful if your Blazor WebAssembly app has large dependencies that are only used for specific parts of the app.

To delay the loading of an assembly, you add it to the BlazorWebAssemblyLazyLoad item group in your project file:

Assemblies marked for lazy loading must be explicitly loaded by the app before they are used. To lazy load assemblies at runtime, use the LazyAssemblyLoader service:

@inject LazyAssemblyLoader LazyAssemblyLoader @code { var assemblies = await LazyAssemblyLoader.LoadAssembliesAsync(new string[] { "Lib1.dll" });
}

To lazy load assemblies for a specific page, use the OnNavigateAsync event on the Router component. The OnNavigateAsync event is fired on every page navigation and can be used to lazy load assemblies for a particular route. You can also lazily load the entire page for a route by passing any lazy loaded assemblies as additional assemblies to the Router.

The following examples demonstrates using the LazyAssemblyLoader service to lazy load a specific dependency (Lib1.dll) when the user navigates to /page1. The lazy loaded assembly is then added to the additional assemblies list passed to the Router component, so that it can discover any routable components in that assembly.

@using System.Reflection
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.WebAssembly.Services
@inject LazyAssemblyLoader LazyAssemblyLoader <Router AppAssembly="typeof(Program).Assembly" AdditionalAssemblies="lazyLoadedAssemblies" OnNavigateAsync="@OnNavigateAsync"> <Navigating> <div> <p>Loading the requested page...</p> </div> </Navigating> <Found Context="routeData"> <RouteView RouteData="@routeData" DefaultLayout="typeof(MainLayout)" /> </Found> <NotFound> <LayoutView Layout="typeof(MainLayout)"> <p>Sorry, there is nothing at this address.</p> </LayoutView> </NotFound>
</Router> @code { private List<Assembly> lazyLoadedAssemblies = new List<Assembly>(); private async Task OnNavigateAsync(NavigationContext args) { if (args.Path.EndsWith("/page1")) { var assemblies = await LazyAssemblyLoader.LoadAssembliesAsync(new string[] { "Lib1.dll" }); lazyLoadedAssemblies.AddRange(assemblies); } }
}

Updated Blazor WebAssembly globalization support

.NET 5 Preview 8 reintroduces globalization support for Blazor WebAssembly based on International Components for Unicode (ICU). Part of introducing the ICU data and logic is optimizing these payloads for download size. This work is not fully completed yet. We expect to reduce the size of the ICU data in future .NET 5 preview updates.

New InputRadio Blazor component

Blazor in .NET 5 now includes built-in InputRadio and InputRadioGroup components. These components simplify data binding to radio button groups with integrated validation alongside the other Blazor form input components.

Opinion about blazor:
<InputRadioGroup @bind-Value="survey.OpinionAboutBlazor"> @foreach (var opinion in opinions) { <div class="form-check"> <InputRadio class="form-check-input" id="@opinion.id" Value="@opinion.id" /> <label class="form-check-label" for="@opinion.id">@opinion.label</label> </div> }
</InputRadioGroup>

Set UI focus in Blazor apps

Blazor now has a FocusAsync convenience method on ElementReference for setting the UI focus on that element.

<button @onclick="() => textInput.FocusAsync()">Set focus</button>
<input @ref="textInput"/>

IAsyncDisposable support for Blazor components

Blazor components now support the IAsyncDisposable interface for the asynchronous release of allocated resources.

Control Blazor component instantiation

You can now control how Blazor components are instantiated by providing your own IComponentActivator service implementation.

Thank you Mladen Macanović for this Blazor feature contribution!

Influencing the HTML head in Blazor apps

Use the new Title, Link, and Meta components to programmatically set the title of a page and dynamically add link and meta tags to the HTML head in a Blazor app.

To use the new Title, Link, and Meta components:

  1. Add a package reference to the Microsoft.AspNetCore.Components.Web.Extensions package.
  2. Include a script reference to _content/Microsoft.AspNetCore.Components.Web.Extensions/headManager.js.
  3. Add a @using directive for Microsoft.AspNetCore.Components.Web.Extensions.Head.

The following example programmatically sets the page title to show the number of unread user notifications, and updates the page icon a as well:

@if (unreadNotificationsCount > 0)
{ var title = $"Notifications ({unreadNotificationsCount})"; <Title Value="title"></Title> <Link rel="icon" href="icon-unread.ico" />
}

Protected browser storage

In Blazor Server apps, you may want to persist app state in local or session storage so that the app can rehydrate it later if needed. When storing app state in the user’s browser, you also need to ensure that it hasn’t been tampered with.

Blazor in .NET 5 helps solve this problem by providing two new services: ProtectedLocalStorage and ProtectedSessionStorage. These services help you store state in local and session storage respectively, and they take care of protecting the stored data using the ASP.NET Core data protection APIs.

To use the new protected browser storage services:

  1. Add a package reference to Microsoft.AspNetCore.Components.Web.Extensions.
  2. Configure the services by calling services.AddProtectedBrowserStorage() from Startup.ConfigureServcies.
  3. Inject either ProtectedLocalStorage and ProtectedSessionStorage into your component implementation:

    @inject ProtectedLocalStorage ProtectedLocalStorage
    @inject ProtectedSessionStorage ProtectedSessionStorage
    
  4. Use the desired service to get, set, and delete state asynchronously:

    private async Task IncrementCount()
    {
    await ProtectedLocalStorage.SetAsync("count", ++currentCount);
    }
    

Model binding and validation with C# 9 record types

You can now use C# 9 record types with model binding in an MVC controller or a Razor Page. Record types are a great way to model data being transmitted over the wire.

For example, the PersonController below uses the Person record type with model binding and form validation:

“`C# public record Person([Required] string Name, [Range(0, 150)] int Age);

public class PersonController { public IActionResult Index() => View();

[HttpPost] public IActionResult Index(Person person) { // … } }

<br />*Person/Index.cshtml* ```razor
@model Person Name: <input asp-for="Model.Name" />
<span asp-validation-for="Model.Name" /> Age: <input asp-for="Model.Age" />
<span asp-validation-for="Model.Age" />

Improvements to DynamicRouteValueTransformer

ASP.NET Core in .NET Core 3.1 introduced DynamicRouteValueTransformer as a way to use use a custom endpoint to dynamically select an MVC controller action or a razor page. In .NET 5 Preview 8 you can now pass state to your DynamicRouteValueTransformer and filter the set of endpoints chosen.

Auto refresh with dotnet watch

In .NET 5, running dotnet watch on an ASP.NET Core project will now both launch the default browser and auto refresh the browser as you make changes to your code. This means you can open an ASP.NET Core project in your favorite text editor, run dotnet watch run once, and then focus on your code changes while the tooling handles rebuilding, restarting, and reloading your app. We expect to bring the auto refresh functionality to Visual Studio in the future as well.

Console Logger Formatter

We’ve made improvements to the console log provider in the Microsoft.Extensions.Logging library. Developers can now implement a custom ConsoleFormatter to exercise complete control over formatting and colorization of the console output. The formatter APIs allow for rich formatting by implementing a subset of the VT-100 (supported by most modern terminals) escape sequences. The console logger can parse out escape sequences on unsupported terminals allowing you to author a single formatter for all terminals.

JSON Console Logger

In addition to support for custom formatters, we’ve also added a built-in JSON formatter that emits structured JSON logs to the console. You can switch from the default simple logger to JSON, add to following snippet to your Program.cs:

public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args)
+ .ConfigureLogging(logging =>
+ {
+ logging.AddJsonConsole(options =>
+ {
+ options.JsonWriterOptions = new JsonWriterOptions() { Indented = true };
+ });
+ }) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });

Once enabled, log messages emitted to the console are now JSON formatted.

{ "EventId": 0, "LogLevel": "Information", "Category": "Microsoft.Hosting.Lifetime", "Message": "Now listening on: https://localhost:5001", "State": { "Message": "Now listening on: https://localhost:5001", "address": "https://localhost:5001", "{OriginalFormat}": "Now listening on: {address}" }
}

Give feedback

We hope you enjoy this release of ASP.NET Core in .NET 5! We are eager to hear about your experiences with this latest .NET 5 release. Let us know what you think by filing issues on GitHub.

Thanks for trying out ASP.NET Core!

Posted on Leave a comment

Hybrid Blazor apps in the Mobile Blazor Bindings July update

Eilon Lipton

Eilon

I’m excited to announce we are releasing the Mobile Blazor Bindings July update! This release adds support for building Hybrid Blazor apps, which contain both native and web UI.

Hybrid apps are a composition of native and web UI in a single app. With Mobile Blazor Bindings this means you can write the native UI of your app using Blazor, and also create web UI in your app using Blazor. A major advantage of hybrid apps is that the HTML part of the app can reuse content, layout, and styles that are used in a regular web app, while enabling rich native UI to be composed alongside it. You can reuse code, designs, and knowledge, while still taking full advantage of each platform’s unique features. This feature supports Android, iOS, Windows (WPF), and macOS. And it’s all Blazor, C#, .NET, and Visual Studio. Woohoo!

You can mix and match native and web UI in whatever structure makes sense for your app. Here’s a simple example:

Blazor Hybrid app in iOS Simulator

These are the major new features in the 0.4 Preview 4 release:

  • New Hybrid Apps feature enables mixing Blazor native UI components with Blazor web UI components in the same page. This one is HUGE!
  • Hybrid Apps are hosted in a new BlazorWebView component that uses a browser component to contain the web part of the app. No remote or local web server; all your code runs in the app’s process.
  • New blazorhybrid project template that supports Android, iOS, Windows (WPF), and macOS for creating hybrid apps
  • Updated dependencies: Xamarin.Forms 4.7, Xamarin.Essentials 1.5, and other libraries.
  • .NET Core 3.1 SDK is required to use the new preview

How does it work?

In hybrid apps all the code (both for the native UI parts and the web UI parts) runs as .NET code on the device. There is no local or remote web server and no WebAssembly (WASM). The .NET code for the entire app runs in a single process. The native UI components run as the device’s standard UI components (button, label, etc.) and the web UI components are hosted in a browser view (such as WebKit, Chromium, and Edge WebView2). The components can share state using standard .NET patterns, such as event handlers, dependency injection, or anything else you are already using in your apps today.

Get started

To get started building a Blazor Hybrid app with Experimental Mobile Blazor Bindings preview 4, install the .NET Core 3.1 SDK and then run the following command:

dotnet new -i Microsoft.MobileBlazorBindings.Templates::0.4.74-preview

And then create your first project by running this command:

dotnet new blazorhybrid -o MyHybridApp

Now open it in Visual Studio and run it on Android, iOS, Windows, or macOS. That’s it! You can find additional docs and tutorials on https://docs.microsoft.com/mobile-blazor-bindings/.

Blazor Hybrid code sample

Here’s the code for an app similar to what was seen at the top of this post. It has native UI and web UI sharing the same app state, running together in the same app process (no web server or HTTP). The native UI uses the new <BlazorWebView> component to specify which web component to load and where to locate static web assets. Blazor does all the work.

This is the main native UI page /Main.razor:

@inject CounterState CounterState <ContentView> <StackLayout> <StackLayout Margin="new Thickness(20)"> <Label Text="@($"You pressed {CounterState.CurrentCount} times")" FontSize="30" /> <Button Text="Increment from native" OnClick="@CounterState.IncrementCount" Padding="10" /> </StackLayout> <BlazorWebView ContentRoot="WebUI/wwwroot" VerticalOptions="LayoutOptions.FillAndExpand"> <FirstBlazorHybridApp.WebUI.App /> </BlazorWebView> </StackLayout>
</ContentView> @code { // initialization code
}

And this is the embedded HTML UI page /WebUI/App.razor:

@inject CounterState CounterState <div style="text-align: center; background-color: lightblue;"> <div> <span style="font-size: 30px; font-weight: bold;"> You pressed @CounterState.CurrentCount times </span> </div> <div> <button style="margin: 20px;" @onclick="ClickMe">Increment from HTML</button> </div>
</div> @code
{ private void ClickMe() { CounterState.IncrementCount(); } // initialization code
}

Upgrade an existing project

To update an existing Mobile Blazor Bindings project please refer to the Migrate Mobile Blazor Bindings From Preview 3 to Preview 4 topic for full details.

More information

Check out last month’s ASP.NET Community Standup where I talked a bit about these new features and did a demo of Blazor hybrid apps (starts at 30:35):

For more information please check out:

Thank you to contributors

This release had several major contributions from Jan-Willem Spuij. Jan-Willem had already built his own BlazorWebView component and kindly helped us get this functionality into the Mobile Blazor Bindings project with many great improvements. Thank you Jan-Willem!

What’s next? Let us know what you want!

This project relies on your feedback to help shape the future of Blazor for native and hybrid scenarios. Please share your thoughts on this blog post or at the GitHub repo so we can keep the discussion going.

Posted on Leave a comment

ASP.NET Core Updates in .NET 5 Preview 7

Avatar

Sourabh

.NET 5 Preview 7 is now available and is ready for evaluation. Here’s what’s new in this release:

  • Blazor WebAssembly apps now target .NET 5
  • Updated debugging requirements for Blazor WebAssembly
  • Blazor accessibility improvements
  • Blazor performance improvements
  • Certificate authentication performance improvements
  • Sending HTTP/2 PING frames
  • Support for additional endpoints types in the Kestrel sockets transport
  • Custom header decoding in Kestrel
  • Other minor improvements

Get started

To get started with ASP.NET Core in .NET 5 Preview 7 install the .NET 5 SDK.

You need to use Visual Studio 2019 16.7 Preview 5 or newer to use .NET 5 Preview 7. .NET 5 is also supported with the latest preview of Visual Studio for Mac. To use .NET 5 with Visual Studio Code, install the latest version of the C# extension.

Upgrade an existing project

To upgrade an existing ASP.NET Core app from .NET 5 Preview 6 to .NET 5 Preview 7:

  • Update all Microsoft.AspNetCore.* package references to 5.0.0-preview.7.*.
  • Update all Microsoft.Extensions.* package references to 5.0.0-preview.7.*.
  • Update System.Net.Http.Json package references to 5.0.0-preview.7.*.

See the full list of breaking changes in ASP.NET Core for .NET 5.

Upgrade existing Blazor WebAssembly projects

To upgrade an existing Blazor WebAssembly project, update the following properties:

From

<TargetFramework>netstandard2.1</TargetFramework>
<RazorLangVersoin>3.0</RazorLangVersion>

To

<TargetFramework>net5.0</TargetFramework>
<RuntimeIdentifier>browser-wasm</RuntimeIdentifier>
<UseBlazorWebAssembly>true</UseBlazorWebAssembly>

Also, remove any package references to Microsoft.AspNetCore.Components.WebAssembly.Build, as it is no longer needed.

What’s new?

Blazor WebAssembly apps now target .NET 5

Blazor WebAssembly 3.2 apps have access only to the .NET Standard 2.1 API set. With this release, Blazor WebAssembly projects now target .NET 5 (net5.0) and have access to a much wider set of APIs. Implementing Blazor WebAssembly support for the APIs in .NET 5 is a work in progress, so some APIs may throw a PlatformNotSupportedException at runtime. We’d love to hear from you if you’re blocked by the lack of support for specific APIs.

Updated debugging requirements for Blazor WebAssembly

To enable debugging of Blazor WebAssembly apps in Visual Studio Code, you previously needed to install the JavaScript Debugger (Nightly) extension. This is no longer required as the JavaScript debugger extension is now shipped as part of VS Code. If you’ve previously installed the JavaScript Debugger (Nightly) extension you can now uninstall it. Enabling the preview version of the JavaScript debugger through the Visual Studio Code settings is still required.

Blazor accessibility improvements

The built-in Blazor input components that derive from InputBase now render aria-invalid automatically when the validation fails.

Blazor performance improvements

One of the major areas of investment for Blazor WebAssembly in .NET 5 is improving runtime performance. This is a multifaceted effort. Below are some of the high-level areas being optimized:

  • .NET runtime execution
  • JSON serialization
  • JavaScript interop
  • Blazor component rendering

Improving Blazor WebAssembly runtime performance for .NET 5 in an ongoing effort. This release contains some initial performance improvements, and we expect to share more details on the results of this performance work for future .NET 5 updates.

Certificate authentication performance improvements

We have added caching to certificate authentication in ASP.NET Core. Caching certificate validation significantly improves the performance of certificate authentication. Our benchmarks show a 400% improvement in requests per second once caching was enabled.

You don’t need to make any changes to your app to take advantage of performance improvements; caching is on by default. There are options to tune or disable caching if you wish.

Find out more about certificate authentication in ASP.NET Core in the docs.

Sending HTTP/2 PING frames

HTTP/2 has a mechanism for sending PING frames as a way of ensuring whether an idle connection is still functional. This is especially useful to have when working with long-lived streams that are often idle but only intermittently see activity (for example, gRPC streams). We have added the ability to send periodic PING frames in Kestrel by setting limits on KestrelServerOptions.

public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.ConfigureKestrel(options => { options.Limits.Http2.KeepAlivePingInterval = TimeSpan.FromSeconds(10); options.Limits.Http2.KeepAlivePingTimeout = TimeSpan.FromSeconds(1); }); webBuilder.UseStartup<Startup>(); });

Support for additional endpoints types in the Kestrel sockets transport

Building upon new API introduced in System.Net.Sockets, the sockets transport (default) in Kestrel now allows you to bind to both existing file handles and unix domain sockets. Support for binding to existing file handles enables using the existing Systemd integration without requiring you to use the libuv transport.

Custom header decoding in Kestrel

We added the ability to specify which System.Text.Encoding to use to interpret incoming headers based on the header name instead of defaulting to UTF-8. You can set the RequestHeaderEncodingSelector property on KestrelServerOptions to specify which encoding to use.

public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.ConfigureKestrel(options => { options.RequestHeaderEncodingSelector = encoding => { switch (encoding) { case "Host": return System.Text.Encoding.Latin1; default: return System.Text.Encoding.UTF8; } }; }); webBuilder.UseStartup<Startup>(); });

Other improvements

  • For preview 7, we’ve started applying nullable annotations to ASP.NET Core assemblies. We intend on annotating most of the common public API surface of the framework during the 5.0 release.
  • CompareAttribute can now be applied to properties on Razor Page model.
  • Parameters and properties bound from the body are considered required by default.
  • We’ve started applying nullable annotations to ASP.NET Core assemblies. We intend to annotate most of the common public API surface of the framework during the .NET 5 release.
  • Authorization when using endpoint routing now receives the HttpContext rather than the endpoint instance. This allows the authorization middleware to access the RouteData and other properties of the HttpContext that were not accessible though the Endpoint class. The endpoint can be fetched from the context using context.GetEndpoint().
  • The default format for System.Diagnostics.Activity now defaults to the W3C format. This makes distributed tracing support in ASP.NET Core interoperable with more frameworks by default.
  • CompareAttribute can now be applied to properties on a Razor Page model.
  • FromBodyAttribute now supports configuring an option that allows these parameters or properties to be considered optional:

    C#
    public IActionResult Post([FromBody(EmptyBodyBehavior = EmptyBodyBehavior.Allow)] MyModel model) { ... }

Give feedback

We hope you enjoy this release of ASP.NET Core in .NET 5! We are eager to hear about your experiences with this latest .NET 5 release. Let us know what you think by filing issues on GitHub.

Thanks for trying out ASP.NET Core!

Posted on Leave a comment

ASP.NET Core updates in .NET 5 Preview 6

Avatar

Sourabh

.NET 5 Preview 6 is now available and is ready for evaluation. Here’s what’s new in this release:

  • Blazor WebAssembly template now included
  • JSON extension methods for HttpRequest and HttpResponse
  • Extension method to allow anonymous access to an endpoint
  • Custom handling of authorization failures
  • SignalR Hub filters

Get started

To get started with ASP.NET Core in .NET 5.0 Preview 6 install the .NET 5.0 SDK.

You need to use Visual Studio 2019 16.7 or Visual Studio 2019 for Mac 8.6 to use .NET 5.0. Install the latest version of the C# extension, to use .NET 5.0 with Visual Studio Code.

Upgrade an existing project

To upgrade an existing ASP.NET Core 5.0 Preview 5 app to ASP.NET Core 5.0 Preview 6:

  • Update all Microsoft.AspNetCore.* package references to 5.0.0-preview.6.*.
  • Update all Microsoft.Extensions.* package references to 5.0.0-preview.6.*.

See the full list of breaking changes in ASP.NET Core 5.0.

That’s it! You should now be all set to use .NET 5 Preview 6.

What’s new?

Blazor WebAssembly template now included

The Blazor WebAssembly template is now included in the .NET 5 SDK along with the Blazor Server template. To create a Blazor WebAssembly project, simply run dotnet new blazorwasm.

JSON extension methods for HttpRequest and HttpResponse

You can now easily read and write JSON data from an HttpRequest and HttpResponse using the new ReadFromJsonAsync and WriteAsJsonAsync extension methods. These extension methods use the System.Text.Json serializer to handle the JSON data. You can also check if a request has a JSON content type using the new HasJsonContentType extension method.

The JSON extension methods can be combined with endpoint routing to create JSON APIs in a style of programming we call “route to code”. It is a new option for developers who want to create basic JSON APIs in a lightweight way. For example, a web app that has only a handful of endpoints might choose to use route to code rather than the full functionality of ASP.NET Core MVC.

endpoints.MapGet("/weather/{city:alpha}", async context =>
{ var city = (string)context.Request.RouteValues["city"]; var weather = GetFromDatabase(city); await context.Response.WriteAsJsonAsync(weather);
});

Find out more about the JSON extension methods in a recent On .NET interview about route to code.

Extension method to allow anonymous access to an endpoint

You can now allow anonymous access to an endpoint using the simpler AllowAnonymous extension method when using endpoint routing.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{ app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapGet("/", async context => { await context.Response.WriteAsync("Hello World!"); }) .AllowAnonymous(); });
}

Custom handling of authorization failures

Custom handling of authorization failures is now easier with the new IAuthorizationMiddlewareResultHandler interface that is invoked by the AuthorizationMiddleware. The default implementation remains the same, but a custom handler can be be registered in DI which allows things like custom HTTP responses based on why authorization failed. A sample that demonstrates usage of the IAuthorizationMiddlewareResultHandler can be found here.

SignalR Hub filters

Hub filters, called Hub pipelines in ASP.NET SignalR, is a feature that allows you to run code before and after Hub methods are called, similar to how middleware lets you run code before and after an HTTP request. Common uses include logging, error handling, and argument validation.

You can read more about this Hub filters on the docs page.

Give feedback

We hope you enjoy this release of ASP.NET Core in .NET 5! We are eager to hear about your experiences with this latest .NET 5 release. Let us know what you think by filing issues on GitHub.

Thanks for trying out ASP.NET Core!

Posted on Leave a comment

gRPC-Web for .NET now available

Avatar

James

gRPC-Web for .NET is now officially released. We announced experimental support in January and since then we’ve been making improvements based on feedback from early adopters.

With this release gRPC-Web graduates to a fully supported component of the grpc-dotnet project and is ready for production. Use gRPC in the browser with gRPC-Web and .NET today.

Getting started

Developers who are brand new to gRPC should check out Create a gRPC client and server in ASP.NET Core. This tutorial walks through creating your first gRPC client and server using .NET.

If you already have a gRPC app then the Use gRPC in browser apps article shows how to add gRPC-Web to a .NET gRPC server.

What are gRPC and gRPC-Web

gRPC is a modern high-performance RPC (Remote Procedure Call) framework. gRPC is based on HTTP/2, Protocol Buffers and other modern standard-based technologies. gRPC is an open standard and is supported by many programming languages, including .NET.

It is currently impossible to implement the gRPC HTTP/2 spec in the browser because there are no browser APIs with enough fine-grained control over requests. gRPC-Web is a standardized protocol that solves this problem and makes gRPC usable in the browser. gRPC-Web brings many of gRPC’s great features, like small binary messages and contract-first APIs, to modern browser apps.

New opportunities with gRPC-Web

gRPC-Web is designed to make gRPC available in more scenarios. These include:

  • Call ASP.NET Core gRPC apps from the browser – Browser APIs can’t call gRPC HTTP/2. gRPC-Web offers a compatible alternative.
    • JavaScript SPAs
    • .NET Blazor Web Assembly apps
  • Host ASP.NET Core gRPC apps in IIS and Azure App Service – Some servers, such as IIS and Azure App Service, currently can’t host gRPC services. While this is actively being worked on, gRPC-Web offers an interesting alternative that works in every environment today.
  • Call gRPC from non-.NET Core platforms – HTTP/2 is not supported by HttpClient on all .NET platforms. gRPC-Web can be used to call gRPC services from Blazor and Xamarin.

gRPC loves Blazor and .NET

gRPC is a registered trademark of the Linux foundation. Blazor is compatible with gRPC-web

We’ve worked with the Blazor team to make gRPC-Web a great end-to-end developer experience when used in Blazor WebAssembly apps. Not only will gRPC tooling automatically generate strongly typed clients for you to call gRPC services from your Blazor app, but gRPC offers significant performance benefits over JSON.

A great example of the performance benefits in action is Blazor’s default template app. The data transferred on the fetch data page is halved when gRPC is used instead of JSON. Data size is reduced from 627 bytes down to 309 bytes.

Developer tools showing gRPC-Web transfer size

The performance gain here comes from gRPC’s efficient binary serialization over traditional text-based JSON. gRPC-Web is an exciting opportunity to improve rich browser-based apps.

Try gRPC-Web with ASP.NET Core today

For more information about gRPC-Web, check out the documention, or try out a sample app that uses gRPC-Web.

gRPC-Web for .NET is out on NuGet now:

We look forward to seeing what you create with .NET, gRPC and now gRPC-Web!