从aspx页面获取响应

本文关键字:获取 响应 aspx | 更新日期: 2023-09-27 18:08:22

我想做到最简单的事情。也就是说,从c#控制台应用程序请求一个aspx页面,然后aspx页面应该返回一个字符串给c#应用程序。

我找了很多地方,但没有找到任何东西:(

假设我的页面名为www.example.com/default.aspx。从我的c#应用程序中,我向该页发出请求,然后该页应该返回一个字符串,说"Hello"。

下面,我用伪代码写了我认为应该怎么做。

c#应用

public static void Main(string[] args)
{
    //1. Make request to the page: www.example.com/default.aspx
    //2. Get the string from that page.
    //3. Write out the string. (Should be "Hello")
    Console.ReadLine();
}

。aspx代码

public partial class Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string text = "Hello";
        //1. Return the "text" variable to the client that requested this page
    }
}

从aspx页面获取响应

使用System.Net.WebClient类

var html = new WebClient().DownloadString("http://www.example.com/default.aspx"));
Console.Write(html);

网页应该输出文本为

Response.Write(text);

你可以这样做:

protected void Page_Load(object sender, EventArgs e)
    {
        string text = "Hello";
        //1. Return the "text" variable to the client that requested this page
              Response.ContentType = "text/plain";
              Response.BufferOutput = false;
              Response.BinaryWrite(GetBytes(text));
              Response.Flush();
              Response.Close();
              Response.End();
    }
static byte[] GetBytes(string str)
{
    byte[] bytes = new byte[str.Length * sizeof(char)];
    System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
    return bytes;
}
从控制台

WebRequest request = WebRequest.Create ("http://www.contoso.com/yourPage.aspx");
            HttpWebResponse response = (HttpWebResponse)request.GetResponse ();
            Stream dataStream = response.GetResponseStream ();
            StreamReader reader = new StreamReader (dataStream);
            string responseFromServer = reader.ReadToEnd ();
            Console.WriteLine (responseFromServer);
            reader.Close ();
            dataStream.Close ();
            response.Close ();