SILVERLIGHT访问WCF时通过WEB.CONFIG 指定服务器地址

在部署SILVERLIGHT站点时,需要能够修改WCF服务的地址,在网上搜索了多篇文章,程序改造成功。过程总结如下

1.在WEB.CONFIG中添加配置节点

<appSettings>
<add key ="WCFServiceAddress" value ="http://192.168.100.107/ProspectTaskWcfService/SilverLight_Service.svc"/>
</appSettings >

2.在host Silverilght 的aspx页面中添加<param name="initParams" vaule=""/>,添加完成后,如下所示:

<param name="source" value="ClientBin/Jurassic.ProspectTask.Web.Control.WorkPlan.xap"/>
<param name="onerror" value="onSilverlightError" />
<param name="background" value="white" />
<param name="minRuntimeVersion" value="3.0.40624.0" />
<param name="autoUpgrade" value="true" />
<param name="initParams" value="wcfServiceUrl=<%=ConfigurationManager.AppSettings["WCFServiceAddress"] %> " />

我们要是想给SILVERLIGHT传点别的什么东西,也可以用这种方式,下边是传多个参数的例子

<param name="initParams" value="wcfServiceUrl=<%=ConfigurationManager.AppSettings["WCFServiceAddress"] %>,webSiteUrl=<%=ConfigurationManager.AppSettings["WebSite"] %> " />

3.在SilverLight工程下App.xmal.cs中,添加属性CustomConfigurations,并修改事件Application_Startup。如下所示

        private  IDictionary<string, string> _customConfigurations;
        public IDictionary<string, string> CustomConfigurations
        {
            get { return _customConfigurations; }
        }

        public App()
        {
            this.Startup += this.Application_Startup;
            this.Exit += this.Application_Exit;
            this.UnhandledException += this.Application_UnhandledException;

            InitializeComponent();
        }

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            _customConfigurations = e.InitParams;
            this.RootVisual = new MainPage();
            
        }

4.在SilverLight工程中添加一个新CLASS,用于返回一个连接的实例

public class WcfService
    {
        public WcfService()
        {
        }

        public SilverService.SilverLightClient GetWCF()
        {
            App application = (App)Application.Current;
            string url = application.CustomConfigurations["wcfServiceUrl"];

            BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.None);
            binding.MaxReceivedMessageSize = int.MaxValue;
            binding.MaxBufferSize = int.MaxValue;
            //
            SilverService.SilverLightClient client = new SilverService.SilverLightClient(binding, new EndpointAddress(new Uri(url)));
            return client;
        }
    }

在我们需要调用WCF服务时,就可通过上边的方法获取实例了

            WcfService wcf = new WcfService();
            SilverService.SilverLightClient client = wcf.GetWCF();
            client.UpdatePlanCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(OnCompleted);
            client.UpdatePlanAsync(_planEntity);
posted on 2011-05-13 14:43  天堂的旁边  阅读(2181)  评论(6编辑  收藏  举报