在Silverlight beta 2 中,所有的 Network Communication 都只提供了APM的方式,调用方法都很简单
话多浪费时间,源码附上先
AccessPolicyDemo.xaml.cs:
Code
public partial class AccessPolicyDemo : UserControl
{
private delegate void DispatcherInvoke(string param);
public AccessPolicyDemo()
{
InitializeComponent();
}
private void Button1_Click(object sender, RoutedEventArgs e)
{
Uri uri = new Uri("http://localhost/SLDemoWeb/Default.aspx"); WebRequest request = WebRequest.Create(uri);
request.Method = "POST";
request.BeginGetRequestStream((AsyncCallback)RequestHandler, request);
}
private void RequestHandler(IAsyncResult ar)
{
WebRequest request = ar.AsyncState as WebRequest;
using (StreamWriter sw = new StreamWriter(request.EndGetRequestStream(ar)))
{
sw.Write("Silverlight is perfect platform.");
}
request.BeginGetResponse((AsyncCallback)ResponseHandler, request);
}
private void ResponseHandler(IAsyncResult ar)
{
WebRequest request = ar.AsyncState as WebRequest;
using (WebResponse response = request.EndGetResponse(ar))
{
using (Stream streram = response.GetResponseStream())
{
using (StreamReader sr = new StreamReader(streram))
{
Result.Dispatcher.BeginInvoke((DispatcherInvoke)ShowResult,sr.ReadToEnd());
}
}
}
}
void ShowResult(string result)
{
Result.Text = result;
}
}
页面代码就不用帖了,就一个Button + TextBlock
下面是default.aspx.cs的
Code
protected void Page_Load(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder("The content that client send to server:\r\n");
if (Request.InputStream == null || Request.InputStream.Length <= 0)
sb.Append("Fuck,it's nothing.");
else
using (Stream inputStream = Request.InputStream)
{
using (StreamReader sr = new StreamReader(inputStream))
{
sb.Append(sr.ReadToEnd());
}
}
Response.Write(sb.ToString());
Response.End();
}
运行后结果的screenshot
在找资料学习的时候,找到一个老外写的一个HttpWebRequest的helper class,很好用的,详细点这里查看
关于跨域访问下集再说
好了,我的第一篇博文就这样了。