[英]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.