繁体   English   中英

从aspx页面获取响应

[英]Get response from aspx page

我想实现最简单的事情。 那就是从ac#控制台应用程序请求一个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
    }
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM