silverlight   发布时间:2022-05-04  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Silverlight 2.0 正式版跨域提交数据全攻略大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

概述

【注】本文代码基于 Silverlight 2.0 正式版。   Silverlight 2.0 正式版发布之后,在 httpWebrequest 方面也发生了一些变化,以前的代码正式版里面可能就无法运行了,具体的 变化主要有:  1,在调用 httpWebrequest.beginGetResponse() 之前,request 流必须关闭;  2,httpWebrequest.EndGetRe
@H_772_15@

【注】本文代码基于 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 @R_772_10495@ng postData = @R_772_10495@ng.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=" + datetiR_366_11845@e.Now.Ticks.To@R_772_10495@ng(),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();
        }
    }
}

 

测试结果:

Silverlight 2.0 正式版跨域提交数据全攻略

大佬总结

以上是大佬教程为你收集整理的Silverlight 2.0 正式版跨域提交数据全攻略全部内容,希望文章能够帮你解决Silverlight 2.0 正式版跨域提交数据全攻略所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。