[转]Silverlight 2.0 正式版跨域提交数据

Silverlight 2.0 正式版跨域提交数据
【注】本文代码基于 Silverlight 2.0 正式版。

Silverlight 2.0 正式版发布之后,在 HttpWebrequest 方面也发生了一些变化,以前的代码正式版里面可能就无法运行了,具体的变化主要有:

1,在调用 HttpWebRequest.BeginGetResponse() 之前,Request 流必须关闭;

2,HttpWebRequest.EndGetResponse() 抛出的异常,正式版之前,HttpWebRequest.BeingGetResponse() 中跨域、跨协议访问抛出安全性异常,其他的请求都返回404错误,现在,HttpRequest.EndGetResponse()的错误将作为异常抛出,涉及安全问题的错误抛出 SecurityException,非成功的请求会抛出 WebException 异常,WebException.Response 被设置成 HttpStatusCode.NotFound。

由于 HttpWebrequest 发送的是异步请求,如果要与界面交互,还涉及到线程同步的问题,如果不进行线程同步,会报告“跨线程访问无效”的错误。下面就以实际的例子来向一个 Java Servlet 地址提交数据,将提交的数据返回到当前界面中。当然,提交到 aspx 页面上也没有问题的,只需要在 Page_Load 事件处理方法里加入下面的代码即可:

protected void Page_Load(object sender, EventArgs e) { if (Request.RequestType.Equals("POST")) { Response.ClearContent(); Response.ClearHeaders(); Response.Write("您提交的数据是:" + Request.Params.Get("data")); Response.End(); return; } }

如果提交到 Java Servlet,则测试代码可以写:

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().print("您提交的数据是:" + request.getParameter("data")); }

要在本机进行跨域测试,需要在hosts文件进行设置,如:

127.0.0.1 www.mengxianhui.com 127.0.0.1 www.xianhuimeng.com

这样,就可以在你自己的机器上进行跨域测试了,不过,需要记住,默认情况下,Silverlight 是不允许跨域访问的,因此,需要在接收数据的网站根目录下(记住是网站根目录,不是应用程序的根目录)放置一个策略文件,clientaccesspolicy.xml 或者 crossdomain.xml :

clientaccesspolicy.xml 内容设置如下:

<?xml version="1.0" encoding="utf-8" ?> <access-policy> <cross-domain-access> <policy> <allow-from http-request-headers="*"> <domain uri="*" /> </allow-from> <grant-to> <resource path="/" include-subpaths="true" /> </grant-to> </policy> </cross-domain-access> </access-policy>

crossdomain.xml 内容设置如下:

<?xml version="1.0" ?> <!doctype cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd"> <cross-domain-policy> <allow-http-request-headers-from domain="*" headers="*" /> </cross-domain-policy>

本例子中使用的 Page.xaml 如下:

<usercontrol xmlns:basics="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls" x:class="SilverlightApplication3.Page" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" width="400" height="300"> <grid x:name="LayoutRoot" background="White"> <canvas width="400" height="300" Canvas. left="2"> <textbox x:name="data" Canvas. left="2" Canvas. top="2" height="30" width="180" text="【孟子E章】测试数据" fontsize="16"></textbox> <button content="发送POST数据" width="100" height="30" click="PostData" Canvas. top="2" Canvas. left="200"></button> <textblock x:name="result" Canvas. top="40" fontsize="16"></textblock> </canvas> </grid> </usercontrol>

Page.xaml.cs 完整内容

using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using System.Text; using System.IO; using System.Diagnostics; using System.Threading; namespace SilverlightApplication3 { public partial class Page : UserControl { public Page() { InitializeComponent(); //设置当前界面线程 syncContext = SynchronizationContext.Current; } private SynchronizationContext syncContext; private String postData = String.Empty; private void PostData(object sender, RoutedEventArgs e) { //请注意:Silverlight 里的 HttpWebRequest, Encoding 类的属性和方法与常规的 .NET Framework 里面还是不同的。 result.Text = "开始提交数据……"; postData = "data=" + data.Text; //要提交的内容 Uri url = new Uri("http://www.mengxianhui.com/admin?tmp=" + DateTime.Now.Ticks.ToString(), UriKind.Absolute); System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; // Silverlight 只支持 GET 和 POST 方法 request.AllowReadStreamBuffering = true; request.ContentType = "application/x-www-form-urlencoded"; request.BeginGetRequestStream(new AsyncCallback(RequestReady), request); } private void RequestReady(IAsyncResult asyncResult) { HttpWebRequest request = asyncResult.AsyncState as HttpWebRequest; StreamWriter postStream = new StreamWriter(request.EndGetRequestStream(asyncResult)); //byte[] byteArray = Encoding.UTF8.GetBytes(postData); //Encoding.GetEncoding()方法只支持四种编码。utf-8 , utf-16 , utf-16BE , utf-16LE postStream.Write(postData); //处理中文的问题。不要使用 Stream 的 Write 方法。 postStream.Close(); postStream.Dispose(); request.BeginGetResponse(new AsyncCallback(ResponseReady), request); } void ResponseReady(IAsyncResult asyncResult) { HttpWebRequest request = asyncResult.AsyncState as HttpWebRequest; WebResponse response = request.EndGetResponse(asyncResult) as WebResponse; //同步线程上下文 if (syncContext == null) syncContext = new SynchronizationContext(); syncContext.Post(ExtractResponse, response); } private void ExtractResponse(object state) { WebResponse response = state as WebResponse; Stream responseStream = response.GetResponseStream(); StreamReader streamRead = new StreamReader(responseStream); //显示返回的数据 result.Text = new StreamReader(responseStream).ReadToEnd(); response.Close(); responseStream.Close(); responseStream.Dispose(); streamRead.Close(); streamRead.Dispose(); } } }
 
http://dotnet.aspx.cc/article/95e21a06-795f-46f5-952e-77bc31b7538f/read.aspx
作者:【孟子E章】 发表于:2008-10-28 00:00:00
posted @ 2008-11-25 17:28  IamV  阅读(346)  评论(0编辑  收藏  举报