从aspx页面获取响应

时间:2014-06-12 10:48:18

标签: c# asp.net request response

我想要实现最简单的事情。这是从c#控制台应用程序请求一个aspx页面,然后aspx页面应该给c#app返回一个字符串。

我搜索了很多,但实际上找不到任何东西:(

让我们说我的网页名为www.example.com/default.aspx。从我的C#应用​​程序,我向该页面发出请求,然后该页面应该返回一个字符串“Hello”。

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

C#app

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

2 个答案:

答案 0 :(得分:3)

使用System.Net.WebClient类

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

网页应将文本输出为

Response.Write(text);

答案 1 :(得分:1)

你可以这样做:

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 ();