8
votes

I am wondering if i am missing something but just started a basic template for server side Blazor and find that Console.WriteLine does not work. By that I mean I can't see the text in Chrome Console.

@code{

    protected override async Task OnInitializedAsync() 
    {
        System.Console.WriteLine("oninit");
    }
}
5
In my case I was using Console.Write("...") which did not work. Console.WriteLine("...") seemed to work though. Not sure why both wouldn't write to the browser console. - Brad Thiessen

5 Answers

22
votes

I had to do something like this to make text show in the browser console:

@inject IJSRuntime jsRuntime

@code {

    protected override async Task OnInitializedAsync()
    {
        await jsRuntime.InvokeAsync<string>("console.log", "hello world");
    }
}
11
votes

When you run it under IIS Express there is indeed no output.

You can use the dropdown on the Run button to select your application by name instead of IIS. And then you will see your output in the console window.

Or use System.Diagnostics.Debug.Print() to see it in the Output Window.

I mean I can't see the text in Chrome Console.

That only happens with Client Side (WebAssembly) Blazor.

4
votes

How to view “Console Output” (i.e. Console.WriteLine statements) for a Blazor App:

  • Go to the Output tab within Visual Studio
  • In the “Show Output from:” drop-down, select your app instead of “Debug”
  • This will now enable you to see any of your Console.Writeline statements to appear now in the Output window within Visual Studio

(This was tested in Visual Studio 2019)

3
votes

You can see in your output window that Console.WriteLine outputs to your app ASP.NET Core Web Server when you are running through IIS Express or as your application. From IIS Express image of IIS Express Output Configuration

As your Application image of running though your application image of your application Output Configuration

If you want to write to your web console you need to work in Client Side Blazor. This is discussed on github discussion page

1
votes

Writing messages in the browser developer tools console. Ueful on Blazor Server. In Blazor WASM we can use Console.WriteLine(), or this same strategy.

@page "/sample-log"
@inject IJSRuntime _js

<!-- html -->

@code {
    protected async override Task OnInitializedAsync()
    {
        await Log("Initialized"); // test
    }

    async ValueTask Log(string text)
    {
        await _js.InvokeVoidAsync("console.log", text);
    }
}