通过命令行创建Blazor项目后在VS Code中出现警告
.NET 8 Blazor Web应用项目的核心问题排查与解决
问题概述
用dotnet new blazor -o ProductBlaze创建.NET 8 Blazor Web应用后,在VS Code里碰到两个问题:
- Routes.razor和解决方案资源管理器弹出警告:
Found markup with unexpected name - Counter.razor里出现错误提示:
The name 'InteractiveServer' does not exist in the current context
已经试过升级C# Dev Kit扩展和.NET版本,问题还是没解决。
解决步骤
1. 修复InteractiveServer不存在的问题
InteractiveServer是.NET 8新增的组件渲染模式枚举,按以下步骤排查:
- 先确认
_Imports.razor里的静态导入是否生效,当前代码已经包含@using static Microsoft.AspNetCore.Components.Web.RenderMode,如果还是报错,直接用完整枚举路径替换:@rendermode Microsoft.AspNetCore.Components.Web.RenderMode.InteractiveServer - 检查项目目标框架是否为.NET 8:打开
ProductBlaze.csproj文件,确保<TargetFramework>的值是net8.0,示例如下:<Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> <TargetFramework>net8.0</TargetFramework> <Nullable>enable</Nullable> <ImplicitUsings>enable</ImplicitUsings> </PropertyGroup> </Project>
2. 解决Found markup with unexpected name警告
这个警告大多是VS Code的C# Dev Kit扩展对Blazor新语法识别延迟,或者项目加载异常导致的:
- 关闭VS Code,删掉项目根目录下的
.vs、.vscode、bin、obj文件夹,重新打开项目 - 用命令行重建项目:
dotnet clean dotnet restore dotnet build - 如果警告还在,试试禁用再重新启用C# Dev Kit扩展,或者换Visual Studio 2022打开项目,验证是不是编辑器本身的问题
修正后的代码示例
_Imports.razor(无需修改,确认保留静态导入)
@using System.Net.Http @using System.Net.Http.Json @using Microsoft.AspNetCore.Components.Forms @using Microsoft.AspNetCore.Components.Routing @using Microsoft.AspNetCore.Components.Web @using static Microsoft.AspNetCore.Components.Web.RenderMode @using Microsoft.AspNetCore.Components.Web.Virtualization @using Microsoft.JSInterop @using ProductBlaze @using ProductBlaze.Components
Counter.razor(两种写法任选其一)
写法1(使用静态导入的枚举):
@page "/counter" @rendermode InteractiveServer <PageTitle>Counter</PageTitle> <h1>Counter</h1> <p role="status">Current count: @currentCount</p> <button class="btn btn-primary" @onclick="IncrementCount">Click me</button> @code { private int currentCount = 0; private void IncrementCount() { currentCount++; } }
写法2(使用完整命名空间路径):
@page "/counter" @rendermode Microsoft.AspNetCore.Components.Web.RenderMode.InteractiveServer <PageTitle>Counter</PageTitle> <h1>Counter</h1> <p role="status">Current count: @currentCount</p> <button class="btn btn-primary" @onclick="IncrementCount">Click me</button> @code { private int currentCount = 0; private void IncrementCount() { currentCount++; } }
内容的提问来源于stack exchange,提问作者JOYBOY
相关产品推荐
相关产品推荐

