调试期间如何在 ASP.NET (C #)中使用 Console. WriteLine?

我想在 ASP.NET (C #)中写一些结果到控制台。 它在 Window 应用程序中可以工作,但 Web 应用程序不能工作。 以下是我试过的方法:

protected void btonClick_Click(object sender, EventArgs e)
{
Console.WriteLine("You click me ...................");
System.Diagnostics.Debug.WriteLine("You click me ..................");
System.Diagnostics.Trace.WriteLine("You click me ..................");
}

但是我在输出面板中没有看到任何东西。我如何解决这个问题?

208106 次浏览

Console.Write will not work in ASP.NET as it is called using the browser. Use Response.Write instead.

See Stack Overflow question Where does Console.WriteLine go in ASP.NET?.

If you want to write something to Output window during debugging, you can use

System.Diagnostics.Debug.WriteLine("SomeText");

but this will work only during debug.

See Stack Overflow question Debug.WriteLine not working.

using System.Diagnostics;

The following will print to your output as long as the dropdown is set to 'Debug' as shown below.

Debug.WriteLine("Hello, world!");


enter image description here

If for whatever reason you'd like to catch the output of Console.WriteLine, you CAN do this:

protected void Application_Start(object sender, EventArgs e)
{
var writer = new LogWriter();
Console.SetOut(writer);
}


public class LogWriter : TextWriter
{
public override void WriteLine(string value)
{
//do whatever with value
}


public override Encoding Encoding
{
get { return Encoding.Default; }
}
}

Trace.Write("Error Message") and Trace.Warn("Error Message") are the methods to use in web, need to decorate the page header trace=true and in config file to hide the error message text to go to end-user and so as to stay in iis itself for programmer debug.

Use response.write method in the code-behind.

Make sure you start your application in Debug mode (F5), not without debugging (Ctrl+F5) and then select "Show output from: Debug" in the Output panel in Visual Studio.

You shouldn't launch as an IIS server. check your launch setting, make sure it switched to your project name( change this name in your launchSettings.json file ), not the IIS.

enter image description here