可能有更好的方法,我愿意使用,但这对我有用,而且很灵活。
在您的 Web 应用程序的 Web.config 中,在 AppSettings 中添加一个变量并存储基本 URL,注意我没有存储 SVC 文件的位置,稍后我会附加它。这是因为我有多个我通常指向的 SVC。你可以选择不同的方式。
<appSettings>
<add key="ServiceURI" value="http://localhost:64457/"/>
</appSettings>
在我的 Web 应用程序的网页中,添加一个名为 InitParms 的参数,这允许您添加键、对值列表(由 XAP 文件读取的逗号分隔)
<div id="silverlightControlHost">
<object data="data:application/x-silverlight," type="application/x-silverlight-2"
width="100%" height="100%" ID="Xaml1" >
<param name="InitParams" value="ServiceURI=<%= ConfigurationManager.AppSettings("ServiceURI") %>" />
在 Silverlight App.xaml.vb 中,将所有 InitParms 加载到资源或您想要的任何位置
Private Sub Application_Startup(ByVal o As Object, ByVal e As StartupEventArgs) Handles Me.Startup
If e.InitParams IsNot Nothing Then
For Each k As Generic.KeyValuePair(Of String, String) In e.InitParams
Me.Resources.Add(k.Key, k.Value)
Next
End If
然后在我的任何 XAML 文件中,我可以使用配置的 URI 初始化服务,我有这样的方法
Private Sub InitializeService()
Dim uri As String = App.Current.Resources("ServiceURI")
If uri Is Nothing OrElse uri = String.Empty Then
'if there is no value added in the web.config, I can fallback to default values
_client = New ServiceClient
Else
'Notice I hardcoded the location of the SVC files in the client and append there here, you may choose not to do this
Dim uri_withservice As String = uri & "svc/secure/Service.svc"
_client = New ServiceClient("CustomBinding_Service", New EndpointAddress(uri_withservice))
End If
End Sub