我通常会这样做:
Console.WriteLine("My debug output.");
如果你正在使用的是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.
ILogger<T>
,这将使您有可能在控制台上写入警告或错误信息:@using Microsoft.Extensions.Logging
@inject ILogger<MyComponent> _logger
...
@code {
protected override void OnInitialized()
{
_logger.LogWarning("warning");
_logger.LogError("error");
}
}
LogWarning
使用console.warning,LogError
使用console.error,LogInformation
使用console.info,LogTrace
使用console.trace。 - undefined
@inject IJSRuntime JS
...
@code {
protected override async void OnInitialized()
{
await JS.InvokeVoidAsync("console.log","loaded");
}
}
有关从Blazor调用JS函数的更多信息:https://learn.microsoft.com/en-us/aspnet/core/blazor/javascript-interoperability/call-javascript-from-dotnet?view=aspnetcore-6.0
在@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);
}
}
Console.WriteLine("My debug output.");
输出调试信息。 - Alexan