標籤:blog http tar ext com get
在Windows metro app中調用wcf服務可以通過添加 “服務引用”來實現。一旦項目發布則不可修改。這個和案頭開發不一樣。
現在我們通過讀取文本的方式來讀取wcf地址。
1、添加所需引用的wcf 地址。
2、添加完之後。自動產生的Reference.cs裡面我們可以看到 private static System.ServiceModel.EndpointAddress GetEndpointAddress(EndpointConfiguration endpointConfiguration)這個方法裡面有我們添加的地址。我們知道在這個方法裡面去讀取文本是不可行的。因為這個方法不支援非同步(async)。
3、我們把讀取文本中的地址放到 App.xaml.cs 的 OnLaunched 方法中去讀取。然後把讀到的地址放到全域變數中。
在Reference.cs中讀取該全域變數。
app.xaml.cs下的代碼:
protected override async void OnLaunched(LaunchActivatedEventArgs args)
{
var key = await ReadWCFService();
var localSettings = ApplicationData.Current.LocalSettings;
if (localSettings.Values.ContainsKey("WCFAPI"))
localSettings.Values["WCFAPI"] = key;
else
localSettings.Values.Add("WCFAPI", key);
}
/// <summary>
/// 讀取設定檔
/// </summary>
/// <returns></returns>
public async Task<string> ReadWCFService()
{
try
{
var storageFolder = KnownFolders.DocumentsLibrary;
var file = await storageFolder.GetFileAsync("WcfServiceUrl.txt");
var str = await FileIO.ReadTextAsync(file);
return str.Trim();
}
catch (Exception e)
{
}
return string.Empty;
}
Reference.cs下的代碼:
private static System.ServiceModel.EndpointAddress GetEndpointAddress(EndpointConfiguration endpointConfiguration) {
if ((endpointConfiguration == EndpointConfiguration.BasicHttpBinding_IService1)) {
var str = string.Empty;
var localSettings = ApplicationData.Current.LocalSettings;
if (localSettings.Values.ContainsKey("WCFAPI"))
{
str = localSettings.Values["WCFAPI"].ToString();
}
return new System.ServiceModel.EndpointAddress(str);
}
throw new System.InvalidOperationException(string.Format("Could not find endpoint with name \‘{0}\‘.", endpointConfiguration));
}