如何通过Blazor WebAssembly将内容写入浏览器控制台?

46

在JavaScript中,我们可以使用以下方法将调试输出写入浏览器控制台:

console.log("My debug output.");

Google Chrome的输出结果:

console output in google chrome

如何通过Blazor WebAssembly在我的组件中将"My debug output"记录到浏览器控制台?

<button @onclick="ClickEvent">OK</button>

@code {

    private void ClickEvent()
    {
        // console.log("My debug output.");
    }
}

1
我认为你可以使用大写的C#来完成这个任务,使用Console.WriteLine("My debug output.");输出调试信息。 - Alexan
5个回答

80

我通常会这样做:

Console.WriteLine("My debug output.");

如果是Blazor WebAssembly,我会在浏览器控制台中看到消息。
如果是Blazor Server App,我会在输出窗口中看到消息。(在输出窗口中,有一个下拉菜单 - 选择:“ ASP.NET Core Web Server”)。

比我想象的容易。Console.WriteLine("My debug output."); 跨浏览器兼容吗? - Simon
适用于Edge、Chrome和FF。谢谢。 - Simon

44

如果你正在使用的是Blazor Server(而不是WebAssembly),那么你只能使用JSInterop来写入浏览器控制台。我编写了一个类似于以下代码的包装类:

public class JsConsole
{
   private readonly IJSRuntime JsRuntime;
   public JsConsole(IJSRuntime jSRuntime)
   {
       this.JsRuntime = jSRuntime;
   }

   public async Task LogAsync(string message)
   {
       await this.JsRuntime.InvokeVoidAsync("console.log", message);
   }
}

然后在您的页面中,您可以注入JsConsole并使用它:

await this.JsConsole.LogAsync(message); //Will show in the browser console.

4
这是最佳实现方式。我建议将其改为接受一个“对象”而不是一个“字符串”参数,因为JavaScript的“console.log()”方法可以接受任何对象并将其输出为一个字符串或一个JavaScript对象,在日志中提供更好的格式。 - DLeh

21
您可以使用 ILogger<T>,这将使您有可能在控制台上写入警告或错误信息:
@using Microsoft.Extensions.Logging
@inject ILogger<MyComponent> _logger
...
@code {

     protected override void OnInitialized()
     {
          _logger.LogWarning("warning");
          _logger.LogError("error");
     }
}


我假设这只使用console.log级别,而不使用console.error、console.warning、console.info,根据记录的消息级别来看是这样的吗? - undefined
1
@Kissaki,LogWarning使用console.warning,LogError使用console.error,LogInformation使用console.info,LogTrace使用console.trace。 - undefined

7

2

在@Greg Gum的回答基础上,javascript的console.log()也可以接受任何对象。因此,如果你发送一个对象,你将得到完整对象作为javascript对象的漂亮输出,而不仅仅是一个字符串。

public class JsConsole
{
   private readonly IJSRuntime JsRuntime;
   public JsConsole(IJSRuntime jSRuntime)
   {
       this.JsRuntime = jSRuntime;
   }

   //change this parameter to object
   public async Task LogAsync(object message)
   {
       await this.JsRuntime.InvokeVoidAsync("console.log", message);
   }
}

在 Blazor WebAssembly 中,我是这样使用它的:在 SharedProject 中添加一个名为 JsConsole.cs 的类(添加 using Microsoft.JSInterop;),在 Client-Project 的 Program.cs 中将其添加为 Scoped Service,并在 TemplatePage FetchData(Weatherforcast) 中注入它。在 OnInitializedAsync() 中调用它... await JsConsole.LogAsync(forecasts); -> 您将在浏览器控制台中获得 "预报" 表。很好,谢谢 DLeh. - nogood

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接