silverlight中获取网页代码示例

在silverlight中如果要跨域访问,则需要在被访问网站的根目录下添加策略文件crossdomain.xml。内容如下(可以更细致配置,可以查阅相关资料):

 

<?xml version="1.0"?>
<!-- http://localhost/crossdomain.xml -->
<cross-domain-policy>
    <allow-access-from domain="*" />
</cross-domain-policy>

 

 

在silverlight中使用webclient来获取网页内容,这里我简单封装了一个类。

需要using System.Net;

 

 

    public class SuperWebRequest
    {
        public SuperWebRequest(string url, Delegate onComplete)
        {
            requestURL = url;

            webClientOnCompet = onComplete;
            webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
            Random rand = new Random();

            bool add_flag = false;
            for (int i = 0; i < url.Length; i++)
            {
                if (url[i] == '?')
                {
                    add_flag = true;
                    break;
                }
            }
            Uri endpoint;
            if (add_flag)
                endpoint = new Uri(url + "&rand=" + rand.Next());
            else
                endpoint = new Uri(url + "?rand=" + rand.Next());//添加随机数防止缓存
            webClient.DownloadStringAsync(endpoint);
        }

        private void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (!e.Cancelled && e.Error == null)
            {
                //回调
                Super.objMainPage.Dispatcher.BeginInvoke(webClientOnCompet, e.Result.ToString());
            }
            else
            {
                MessageBox.Show("web通信异常" + e.Error.Message.ToString());
            }
        }

        private WebClient webClient = new WebClient();
        private Delegate webClientOnCompet;

        private string requestURL;
    }

 

 

使用方法:

 

定义带模板委托

    public delegate void DelegateSingleParam<T>(T t);

 

调用

                SuperWebRequest myWebRequest = new SuperWebRequest(
                    Config.WebRoot+"lastvolumn.xml", new DelegateSingleParam<string>(OnLoadLastVolumn));

 

回调: data即网页代码

        private void OnLoadLastVolumn(string data)
        {
            
        }

 

你可能感兴趣的:(xml,Web,.net,Access,silverlight)