Windows metro app wcf 地址可配置

來源:互聯網
上載者:User

標籤: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));
}

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.