.NET 8 Blazor Auto模式下JS调用C#的配置问题及代码需求
.NET 8 Blazor Auto模式下JS与C#交互问题解答及完整代码
问题解答
1. app.js应放置在哪个位置?
建议放在BlazorTest.Client项目的wwwroot目录下。Auto模式同时支持Server和WebAssembly交互,Client项目的wwwroot资源会被打包到前端,既能被Wasm客户端直接访问,也能通过Server项目的依赖引用被加载,兼顾两种渲染模式的需求。如果只针对Server模式,也可放在Server项目的wwwroot,但跨端场景下Client的wwwroot是更通用的选择。
2. 如何在BlazorTest项目的App.razor中引用Client项目的app.js?
Client项目的wwwroot资源会被发布到_content/BlazorTest.Client路径下,因此在App.razor中通过该路径引用即可:
<script src="_content/BlazorTest.Client/app.js"></script>
3. C#方法应放在哪个项目?
必须放在BlazorTest.Client项目中。因为DotNet.invokeMethodAsync的第一个参数是目标程序集名称,这里指定的是"BlazorTest.Client",只有该程序集内的带[JSInvokable]特性的静态方法才能被正确调用。
4. 存放C#方法的Razor文件需设置何种@rendermode?
设置为@rendermode InteractiveAuto即可。Auto模式会根据场景自动切换Server或Wasm渲染,该rendermode能确保组件在两种模式下都能正常加载,JS调用的静态方法也能被正确识别。如果将方法放在非组件的静态类中,则无需设置rendermode,但放在Razor组件里时需要指定该模式。
完整可运行代码
1. BlazorTest.Client项目
wwwroot/app.js(修正拼写错误:SeyHello → SayHello)
window.addEventListener('resize', function () { // 注意程序集名称和方法名拼写一致 DotNet.invokeMethodAsync("BlazorTest.Client", "SayHello") .catch(err => console.error("调用C#方法失败:", err)); });
Shared/ResizeListener.razor
@rendermode InteractiveAuto @code { [JSInvokable] public static void SayHello() { Console.WriteLine("Hello from js"); } }
2. BlazorTest(Server)项目
App.razor
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <base href="/" /> <link rel="stylesheet" href="bootstrap/bootstrap.min.css" /> <link rel="stylesheet" href="app.css" /> <link rel="stylesheet" href="BlazorTest.styles.css" /> <link rel="icon" type="image/png" href="favicon.png" /> <HeadOutlet /> </head> <body> <Routes /> <script src="_framework/blazor.web.js"></script> <!-- 引用Client项目的app.js --> <script src="_content/BlazorTest.Client/app.js"></script> </body> </html>
Pages/Index.razor(添加ResizeListener组件)
@page "/" <PageTitle>Home</PageTitle> <h1>Hello, world!</h1> Welcome to your new app. <!-- 添加监听组件,确保组件被加载,静态方法所在程序集被引用 --> <ResizeListener />
内容的提问来源于stack exchange,提问作者Regestea
相关产品推荐
相关产品推荐

