我可以使用XBAP访问web.config吗?

时间:2011-09-23 15:27:35

标签: xbap

我正在将一个Silverlight 4应用程序移植到WPF / XBAP。该应用程序使用从web.config应用程序设置参数使用asp初始化的initParams。

与Silverlight不同,WPF在StartupEventArgs上缺少InitParams属性。

看起来这似乎是BrowserInteropHelper会帮助我做的事情,但我什么也看不见。

有没有办法在启动时从web.config访问配置参数?

1 个答案:

答案 0 :(得分:0)

我的解决方法是将Web服务添加到托管xbap的网站,并在应用程序启动时使用BrowserInteropHelper.Source调用它来确定端点地址的uri。

public class ConfigService : IConfigService
{
    public WebConfiguration GetWebConfig()
    {
        var outDict = new Dictionary<string, string>();
        foreach (string key in WebConfigurationManager.AppSettings.AllKeys)
        {
            outDict.Add(key, WebConfigurationManager.AppSettings[key]);
        }
        var webconfig = new WebConfiguration();
        webconfig.AppSettings = outDict;
        return webconfig;
    }
}

[DataContract]
public class WebConfiguration
{
    [DataMember]
    public Dictionary<string, string> AppSettings { get; set; }
}

客户端如何调用它:

private void Application_Startup(object sender, StartupEventArgs e)
{
    try
    {
        var b = new System.ServiceModel.BasicHttpBinding();

        string url;

        // when running xbap directly in browser the port is -1
        if(BrowserInteropHelper.Source.Port != -1)
        {
            url = String.Format("http://{0}:{1}/ConfigService.svc",
            BrowserInteropHelper.Source.Host,
            BrowserInteropHelper.Source.Port);
        }
        else
        {
            url = @"http://localhost.:51007/ConfigService.svc";
        }
        var address = new System.ServiceModel.EndpointAddress(url);
        SDDM3.ConfigServiceReference.ConfigServiceClient c = new ConfigServiceClient(b, address);
        c.GetWebConfigCompleted +=new EventHandler<GetWebConfigCompletedEventArgs>(c_GetWebConfigCompleted);
        c.GetWebConfigAsync(url);
        this.MainWindow.Content = new UserControl1();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}
void c_GetWebConfigCompleted(object sender, GetWebConfigCompletedEventArgs e)
{
    if (e.Error == null)
    {
        // MessageBox.Show(e2.Result.
        m_AppSettings = e.Result.AppSettings;
        MessageBox.Show("got appsettings: " +  e.Result.AppSettings.Count.ToString());                
        this.MainWindow.Content = new Page1();
    }
    else
    {
        string msg;
        if (e.UserState != null)
            msg = String.Format("Unable to get config from: \n{0} \n{1}", e.UserState, e.Error.Message);
        else
            msg = String.Format("Unable to get config: \n{0}", e.Error.Message);
        MessageBox.Show(msg);
    }
}