【问题标题】:Get response from aspx page从 aspx 页面获取响应
【发布时间】:2014-06-12 10:48:17
【问题描述】:

我想实现最简单的事情。即从 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
    }
}

【问题讨论】:

标签: c# asp.net request response


【解决方案1】:

使用 System.Net.WebClient 类

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

网页应将文本输出为

Response.Write(text);

【讨论】:

  • 嘿,谢谢你的回答,我得到了字符串,但我也得到了整个 html 源代码。我怎样才能只得到字符串?
  • 页面(.aspx 文件)应该是空的(只在第一行保留
【解决方案2】:

你可以这样做:

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

【讨论】:

  • 好的,但是我应该在我的 c# 应用程序中编写什么代码?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-25
  • 1970-01-01
  • 2012-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多