Blazor ASP.NET Core 5.0

De Banane Atomic
Aller à la navigationAller à la recherche

Links

Create a new app

Bash.svg
# Blazor server
dotnet new blazorserver -o [project-name] --no-https
cd [project-name]
dotnet run

Solution Blazor / Webapi

Bash.svg
# create item/item.sln
dotnet new sln -o item
cd item

dotnet new blazorserver -o item.blazor --no-https 
dotnet new webapi -o item.webapi --no-https

dotnet sln add item.blazor/item.blazor.csproj
dotnet sln add item.webapi/item.webapi.csproj
item/.vscode/tasks.json
{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "build blazor",
            "command": "dotnet",
            "type": "process",
            "args": [
                "build",
                "${workspaceFolder}/item.blazor/item.blazor.csproj",
                "/property:GenerateFullPaths=true",
                "/consoleloggerparameters:NoSummary"
            ],
            "problemMatcher": "$msCompile"
        },
        {
            "label": "build webapi",
            "command": "dotnet",
            "type": "process",
            "args": [
                "build",
                "${workspaceFolder}/item.webapi/item.webapi.csproj",
                "/property:GenerateFullPaths=true",
                "/consoleloggerparameters:NoSummary"
            ],
            "problemMatcher": "$msCompile"
        },
        {
            "label": "build all",
            "dependsOn": [
                "build blazor",
                "build webapi"
            ],
            "group": "build",
            "problemMatcher": []
        }
    ]
}
item/.vscode/launch.json
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "blazor",
            "type": "coreclr",
            "request": "launch",
            "preLaunchTask": "build blazor",
            "program": "${workspaceFolder}/item.blazor/bin/Debug/net5.0/item.blazor.dll",
            "args": [],
            "cwd": "${workspaceFolder}/item.blazor",
            "stopAtEntry": false,
            "serverReadyAction": {
                "action": "openExternally",
                "pattern": "\\bNow listening on:\\s+(https?://\\S+)"
            },
            "env": {
                "ASPNETCORE_ENVIRONMENT": "Development"
            },
            "sourceFileMap": {
                "/Views": "${workspaceFolder}/Views"
            }
        },
        {
            "name": "webapi",
            "type": "coreclr",
            "request": "launch",
            "preLaunchTask": "build webapi",
            "program": "${workspaceFolder}/item.webapi/bin/Debug/net5.0/item.webapi.dll",
            "args": [],
            "cwd": "${workspaceFolder}/item.webapi",
            "stopAtEntry": false,
            "serverReadyAction": {
                "action": "openExternally",
                "pattern": "\\bNow listening on:\\s+(https?://\\S+)"
            },
            "env": {
                "ASPNETCORE_ENVIRONMENT": "Development"
            },
            "sourceFileMap": {
                "/Views": "${workspaceFolder}/Views"
            }
        }
    ],
    "compounds": [
        {
            "name": "blazor / webapi",
            "configurations": [
                "blazor",
                "webapi"
            ],
            "preLaunchTask": "build all"
        }
    ]
}

Pages

Pages/Items.razor
@* url *@
@page "/items"
@* url with a parameter *@
@page "/item/{id:int}"

@* wait for the Items to be loaded *@
@if (items == null)
{
    <p><em>Loading...</em></p>
}
else
{ /* ... */ }
Pages/Items.razor.cs
public partial class Items : ComponentBase
{
    private IReadOnlyCollection<ItemDto> items;

    [Parameter]
    public int Id { get; set; }

    protected override async Task OnInitializedAsync()
    {
        items = await this.ItemClient.GetAsync();
    }
}
Pages/Items.razor.css
/* scoped css only for this page */

Static files

Pages/_Host.cshtml
<head>
    <link rel="stylesheet" href="css/site.css"  />
    <link href="{AssemblyName}.styles.css" rel="stylesheet" /> @* active CSS isolation *@
wwwroot/css/site.css
/* only CSS for the entire app, not a specific page */
  • wwwroot/favicon.ico

LibMan

LibMan is a library manager

Bash.svg
# install the LibMan CLI
dotnet tool install -g Microsoft.Web.LibraryManager.Cli

# create a libman.js file
libman init
# available providers: cdnjs, jsdelivr, unpkg, filesystem

# install bootstrap, only bootstrap.min.css and bootstrap.bundle.min.js
libman install bootstrap@5.0.1 --files dist/css/bootstrap.min.css --files dist/js/bootstrap.bundle.min.js
# default destination path: wwwroot/lib/bootstrap

libman install bootswatch@5.0.1 --files dist/darkly/bootstrap.min.css

# uninstall bootstrap
libman uninstall bootstrap@5.0.1

Data binding

One way

Changes made in the UI doesn't change the binded property.
The onchange event can be used to manually update the property.

Razor.svg
<input type="text" value="@Description"
       @onchange=@((ChangeEventArgs __e) => Description = __e.Value.ToString())
       @onchange=OnInputChanged />

@code {
    string Description { get; set; } = "Text";

    void OnInputChanged(ChangeEventArgs e) => Description = e.Value.ToString();
}

Two way

Razor.svg
@* by default uses the on change event (focus lost) *@
<input type="text" @bind=Description />
@* change to on input event *@
<input type="text" @bind=Description @bind:event="oninput" />

@code {
    string Description { get; set; } = "Text";
}

Form

EditItem.razor
@page "/edititem/{ItemId:int}"
@* to access to Model.Item *@
@using Model

<EditForm Model="@item"
          OnValidSubmit="@HandleValidSubmitAsync"
          OnInvalidSubmit="@HandleInvalidSubmitAsync">

    <button type="submit">Save</button> 
    <button @onclick="Cancel">Cancel</button>           
</EditForm>
EditItem.razor.cs
[Parameter]
public int ItemId { get; set; }

[Inject]
private IItemDataService ItemDataService { get; set; }

private Item item = new Item();

protected override async Task OnInitializedAsync()
{
    item = await ItemDataService.GetItemAsync(ItemId);
}

// when the submit button is clicked and the model is valid
private async Task HandleValidSubmitAsync()
{
    await ItemDataService.UpdateItemAsync(item);
}

// when the submit button is clicked and the model is not valid
private async Task HandleInvalidSubmitAsync()
{

}

Input Checkbox

InputCheckbox requires a cascading parameter of type EditContext.
For example, you can use InputCheckbox inside an EditForm.
Razor.svg
<div class="form-group row">
    <label for="smoker"
           class=" offset-sm-3">
        <InputCheckbox id="smoker"
                       @bind-Value="Employee.Smoker">
        </InputCheckbox>
        &nbsp;Smoker
    </label>
</div>

To have a checkbox without an EditForm use input type="checkbox" instead:

Razor.svg
<label>
    <input type="checkbox" @onchange=OnCheckboxValueChanged />
    &nbsp;Text ...
</label>

@code {
    private void OnCheckboxValueChanged(ChangeEventArgs e)
    {
        var checkboxValue = (bool)e.Value;
    }
}

Migration from ASP.NET Core 3.1 to 5.0

dotnet CLI

Bash.svg
# check the dotnet CLI is well using the .NET Core 5.0
dotnet --info

Update the target framework

MyProject.csproj
<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <!--<TargetFramework>netcoreapp3.1</TargetFramework>-->
    <TargetFramework>net5.0</TargetFramework>

Launch task

.vscode/launch.json
// "program": "${workspaceFolder}/MyApp/bin/Debug/netcoreapp3.1/MyApp.dll",
"program": "${workspaceFolder}/MyApp/bin/Debug/net5.0/MyApp.dll",

Update package reference versions

Update each Microsoft.AspNetCore.* Microsoft.EntityFrameworkCore.* Microsoft.Extensions.* System.Net.Http.Json package reference's version attribute to 5.0.0 or later.

MyProject.csproj
<Project Sdk="Microsoft.NET.Sdk.Web">
  <ItemGroup>
    <!--<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.6">-->
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="5.0.0">

Include a new namespaces

_Imports.razor
@using System.Net.Http
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.Authorization
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web
@using Microsoft.AspNetCore.Components.Web.Virtualization
@using Microsoft.JSInterop
@using {AssemblyName}
@using {AssemblyName}.Shared

MainLayout

Surround the component's HTML markup with a <div> element that has a class attribute set to page.

Shared/MainLayout.razor
<div class="page">
    @* ... *@
</div>

CSS

Add link to AssemblyName.styles.css

Pages/_Host.cshtml
@* last css to be added *@
<link href="{AssemblyName}.styles.css" rel="stylesheet" />

Add new CSS files

Shared/MainLayout.razor.css
.page {
    position: relative;
    display: flex;
    flex-direction: column;
}

.main {
    flex: 1;
}

.sidebar {
    background-image: linear-gradient(180deg, rgb(5, 39, 103) 0%, #3a0647 70%);
}

.top-row {
    background-color: #f7f7f7;
    border-bottom: 1px solid #d6d5d5;
    justify-content: flex-end;
    height: 3.5rem;
    display: flex;
    align-items: center;
}

    .top-row ::deep a, .top-row .btn-link {
        white-space: nowrap;
        margin-left: 1.5rem;
    }

    .top-row a:first-child {
        overflow: hidden;
        text-overflow: ellipsis;
    }

@media (max-width: 767.98px) {
    .top-row:not(.auth) {
        display: none;
    }

    .top-row.auth {
        justify-content: space-between;
    }

    .top-row a, .top-row .btn-link {
        margin-left: 0;
    }
}

@media (min-width: 768px) {
    .page {
        flex-direction: row;
    }

    .sidebar {
        width: 250px;
        height: 100vh;
        position: sticky;
        top: 0;
    }

    .top-row {
        position: sticky;
        top: 0;
        z-index: 1;
    }

    .main > div {
        padding-left: 2rem !important;
        padding-right: 1.5rem !important;
    }
}
Shared/NavMenu.razor.css
.navbar-toggler {
    background-color: rgba(255, 255, 255, 0.1);
}

.top-row {
    height: 3.5rem;
    background-color: rgba(0,0,0,0.4);
}

.navbar-brand {
    font-size: 1.1rem;
}

.oi {
    width: 2rem;
    font-size: 1.1rem;
    vertical-align: text-top;
    top: -2px;
}

.nav-item {
    font-size: 0.9rem;
    padding-bottom: 0.5rem;
}

    .nav-item:first-of-type {
        padding-top: 1rem;
    }

    .nav-item:last-of-type {
        padding-bottom: 1rem;
    }

    .nav-item ::deep a {
        color: #d7d7d7;
        border-radius: 4px;
        height: 3rem;
        display: flex;
        align-items: center;
        line-height: 3rem;
    }

.nav-item ::deep a.active {
    background-color: rgba(255,255,255,0.25);
    color: white;
}

.nav-item ::deep a:hover {
    background-color: rgba(255,255,255,0.1);
    color: white;
}

@media (min-width: 768px) {
    .navbar-toggler {
        display: none;
    }

    .collapse {
        /* Never collapse the sidebar for wide screens */
        display: block;
    }
}.navbar-toggler {
    background-color: rgba(255, 255, 255, 0.1);
}

.top-row {
    height: 3.5rem;
    background-color: rgba(0,0,0,0.4);
}

.navbar-brand {
    font-size: 1.1rem;
}

.oi {
    width: 2rem;
    font-size: 1.1rem;
    vertical-align: text-top;
    top: -2px;
}

.nav-item {
    font-size: 0.9rem;
    padding-bottom: 0.5rem;
}

    .nav-item:first-of-type {
        padding-top: 1rem;
    }

    .nav-item:last-of-type {
        padding-bottom: 1rem;
    }

    .nav-item ::deep a {
        color: #d7d7d7;
        border-radius: 4px;
        height: 3rem;
        display: flex;
        align-items: center;
        line-height: 3rem;
    }

.nav-item ::deep a.active {
    background-color: rgba(255,255,255,0.25);
    color: white;
}

.nav-item ::deep a:hover {
    background-color: rgba(255,255,255,0.1);
    color: white;
}

@media (min-width: 768px) {
    .navbar-toggler {
        display: none;
    }

    .collapse {
        /* Never collapse the sidebar for wide screens */
        display: block;
    }
}
wwwroot/css/site.css
@import url('open-iconic/font/css/open-iconic-bootstrap.min.css');

html, body {
    font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
}

a, .btn-link {
    color: #0366d6;
}

.btn-primary {
    color: #fff;
    background-color: #1b6ec2;
    border-color: #1861ac;
}

.content {
    padding-top: 1.1rem;
}

.valid.modified:not([type=checkbox]) {
    outline: 1px solid #26b050;
}

.invalid {
    outline: 1px solid red;
}

.validation-message {
    color: red;
}

#blazor-error-ui {
    background: lightyellow;
    bottom: 0;
    box-shadow: 0 -1px 2px rgba(0, 0, 0, 0.2);
    display: none;
    left: 0;
    padding: 0.6rem 1.25rem 0.7rem 1.25rem;
    position: fixed;
    width: 100%;
    z-index: 1000;
}

#blazor-error-ui .dismiss {
    cursor: pointer;
    position: absolute;
    right: 0.75rem;
    top: 0.5rem;
}

Clean

Bash.svg
# delete the bin and obj folders
dotnet clean
# clear the NuGet package cache
dotnet nuget locals --clear all

Errors

The framework 'Microsoft.AspNetCore.App', version '3.1.0' was not found

It was not possible to find any compatible framework version
The framework 'Microsoft.AspNetCore.App', version '3.1.0' was not found.
  - The following frameworks were found:
      5.0.6 at [/usr/share/dotnet/shared/Microsoft.AspNetCore.App]
You can resolve the problem by installing the specified framework and/or SDK.
The specified framework can be found at:
  - https://aka.ms/dotnet-core-applaunch?framework=Microsoft.AspNetCore.App&framework_version=3.1.0&arch=x64&rid=arch-x64
The target process exited without raising a CoreCLR started event. Ensure that the target process is configured to use .NET Core. This may be expected if the target process did not run on .NET Core.
The program '[15328] Booky.WebApi.dll' has exited with code 150 (0x96).

Solution: edit the .vscode/launch.json file and replace the netcoreapp3.1 by net5.0

  • ensure to upgrade all the nuget packages so they all target .NET 5
  • clean the nuget packages cache and the projects

The DiscoverDefaultScopedCssItems task could not be loaded from the assembly net46/Microsoft.NET.Sdk.Razor.Tasks.dll

The "Microsoft.AspNetCore.Razor.Tasks.DiscoverDefaultScopedCssItems" task could not be loaded from the assembly /usr/share/dotnet/sdk/5.0.203/Sdks/Microsoft.NET.Sdk.Razor/build/netstandard2.0/../../tasks/net46/Microsoft.NET.Sdk.Razor.Tasks.dll. Invalid Image Confirm that the <UsingTask> declaration is correct, that the assembly and all its dependencies are available, and that the task contains a public class that implements Microsoft.Build.Framework.ITask.

Solution: download the missing net46 directory to /usr/share/dotnet/sdk/5.0.203/Sdks/Microsoft.NET.Sdk.Razor/tasks.

error NU3028 NU3037

error NU3028: Package 'Microsoft.AspNetCore.App.Ref 5.0.0' from source 'https://api.nuget.org/v3/index.json':
The author primary signature's timestamp found a chain building issue: UntrustedRoot: self signed certificate in certificate chain

error NU3037: Package 'Microsoft.AspNetCore.App.Ref 5.0.0' from source 'https://api.nuget.org/v3/index.json':
The author primary signature validity period has expired.

Archlinux:

Bash.svg
# downgrade ca-certificates-mozilla from 3.63 to 3.62
sudo pacman -U /var/cache/pacman/pkg/ca-certificates-mozilla-3.62-1-x86_64.pkg.tar.zst

# copy the VeriSign_Universal_Root_Certification_Authority certificate
sudo cp /etc/ssl/certs/VeriSign_Universal_Root_Certification_Authority.pem /etc/ca-certificates/trust-source/anchors/

# install the latest version of ca-certificates-mozilla
# refresh the nuget cache
dotnet restore --no-cache --force