Windows metro app wcf 地址可配置

在Windows metro app中調用wcf服務能夠經過添加 「服務引用」來實現。一旦項目發佈則不可修改。這個和桌面開發不同。app

如今咱們經過讀取文本的方式來讀取wcf地址。異步

一、添加所需引用的wcf 地址。

二、添加完以後。自動生成的Reference.cs裏面咱們能夠看到 private static System.ServiceModel.EndpointAddress GetEndpointAddress(EndpointConfiguration endpointConfiguration)這個方法裏面有咱們添加的地址。咱們知道在這個方法裏面去讀取文本是不可行的。由於這個方法不支持異步(async)。

三、咱們把讀取文本中的地址放到 App.xaml.cs 的 OnLaunched 方法中去讀取。而後把讀到的地址放到全局變量中。

在Reference.cs中讀取該全局變量。async

app.xaml.cs下的代碼:ide

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);orm

}blog

/// <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;
}string

Reference.cs下的代碼:it

private static System.ServiceModel.EndpointAddress GetEndpointAddress(EndpointConfiguration endpointConfiguration) {
if ((endpointConfiguration == EndpointConfiguration.BasicHttpBinding_IService1)) {io

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)); }

相關文章
相關標籤/搜索