Response.OutputStream.Write的问题

Ami*_*adi 4 c# asp.net

我有这个方法的问题,出于某种原因,我发送请求到我的asp页面,然后读取Response流,我得到我的asp页面的内容以及我写入的数据Response.OutputStream.Write(info, 0, info.Length).

在我的例子中,我将字符串"1"写为字节,客户端程序的输出是:

1<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>

</title></head>
<body>
    <form method="post" action="LauncherLogin.aspx" id="form1">
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE2MTY2ODcyMjlkZMraZTexYtyyQ9NaNN0YMvYIep5peaSEIrDBqxTff6rW" />

    <div>

    </div>
    </form>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

我在收到的回复中不想要这个HTML,我该如何摆脱它?

客户代码(c#程序):

public static string SendInformation(string values)
{
    ASCIIEncoding encoding = new ASCIIEncoding();

    string postData = values;
    byte[] data = encoding.GetBytes(postData);

    // Prepare web request...
    HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serverAddress + commmunicationForm);
    myRequest.Method = "POST";
    myRequest.ContentType = "text/html";
    myRequest.ContentLength = data.Length;
    string result;

    using (Stream stream = myRequest.GetRequestStream())
    {
        stream.Write(data, 0, data.Length);
    }
    using (WebResponse response = myRequest.GetResponse())
    {
        using (var reader = new StreamReader(response.GetResponseStream()))
        {
            result = reader.ReadToEnd();
            return result;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

ASP.aspx.cs代码(服务器端):

if (dt.Rows.Count > 0)
{
    Response.Clear();
    Response.ClearContent();
    Response.ClearHeaders();
    Response.Buffer = false;
    string errNum = dt.Rows[0][0].ToString();
    byte[] info = Encoding.ASCII.GetBytes(errNum);
    Response.OutputStream.Write(info, 0, info.Length);
    Response.Flush();
}
Run Code Online (Sandbox Code Playgroud)

即使我这样做:

string errNum = dt.Rows[0][0].ToString();
byte[] info = Encoding.ASCII.GetBytes(errNum);
Response.OutputStream.Write(info, 0, info.Length);
Response.Flush();
Run Code Online (Sandbox Code Playgroud)

我仍然得到HTML代码:|

我确实试过Response.Clear()和其他.Clear()方法没有成功.

Kar*_*son 5

您的问题是您尝试在页面生命周期中过早更改输出(您试图影响事件处理阶段的总输出).您需要拥有改变Render方法内容的逻辑.您可以覆盖该Render方法,如下所示:

protected override void Render(HtmlTextWriter writer)
{
    // Your logic here
}
Run Code Online (Sandbox Code Playgroud)

阅读ASP.NET页面生命周期概述,以获取有关页面事件及其发生顺序的更多信息.