How to use Console.WriteLine in ASP.NET (C#) during debug?

╄→гoц情女王★ 提交于 2020-01-11 15:01:46

问题


I want to write some result to the console in ASP.NET (C#). It works in a Window application, but a Web application does not work. Here is what I have tried:

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 ..................");
}

But I see nothing in the Output panel. How do I solve this problem?


回答1:


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.




回答2:


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!");





回答3:


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; }
    }
}



回答4:


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.




回答5:


Use response.write method in the code-behind.




回答6:


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.



来源:https://stackoverflow.com/questions/9614218/how-to-use-console-writeline-in-asp-net-c-during-debug

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!