【问题标题】:How can I write into the browser´s console via Blazor WebAssembly?如何通过 Blazor WebAssembly 写入浏览器控制台?
【发布时间】:2020-07-14 11:36:11
【问题描述】:

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

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

谷歌浏览器中的输出:

如何通过 Blazor WebAssembly 将组件中的“我的调试输出”记录到浏览器控制台?

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

@code {

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

【问题讨论】:

  • 我认为你可以在 c# 中使用 Console.WriteLine("My debug output."); 和大写 c

标签: blazor blazor-client-side asp.net-blazor


【解决方案1】:

我通常会这样做:

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

如果是 Blazor WebAssembly,我会在浏览器的控制台中看到该消息。

如果是 Blazor 服务器应用程序,我会在“输出”窗口中看到该消息。 (在输出窗口中,有一个下拉菜单——选择:“ASP.NET Core Web Server”)

希望这会有所帮助...

【讨论】:

  • 比我想象的要容易。是 Console.WriteLine("我的调试输出。");跨浏览器兼容?
  • 适用于 Edge、Chrome 和 FF。谢谢。
  • 什么是输入窗口?
【解决方案2】:

如果您使用 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.Log(message); //Will show in the browser console.

【讨论】:

    【解决方案3】:

    您可以使用ILogger&lt;T&gt;,让您可以在控制台中写入警告或错误:

    @using Microsoft.Extensions.Logging
    @inject ILogger<MyComponent> _logger
    ...
    @code {
    
         protected override void OnInitialized()
         {
              _logger.LogWarning("warning");
              _logger.LogError("error");
         }
    }
    
    
    【解决方案4】:

    对于 Blazor 服务器,您可以只注入 JS 运行时,然后您可以像这样在 .razor 文件中访问它:

    @inject IJSRuntime JS
    ...
    @code {
        protected override async void OnInitialized()
        {
            await JS.InvokeVoidAsync("console.log","loaded");
        }
    }
    

    有关从 Blazor 调用 JS 函数的更多信息:https://docs.microsoft.com/en-us/aspnet/core/blazor/javascript-interoperability/call-javascript-from-dotnet?view=aspnetcore-6.0

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-02
      • 2020-11-15
      • 2021-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-31
      相关资源
      最近更新 更多