c# - 如何强制相对 URI 使用 https?

标签 c# silverlight wcf iis-6 https

我有一个相对 URI:

Uri U = new Uri("../Services/Authenticated/VariationsService.svc", 
                               UriKind.Relative);

问题在于,根据用户是在他们的 Web 浏览器中键入 https://还是 http://来访问 silverlight 应用程序,它在尝试联系该服务时可能会使用 http 或 https。

我想强制程序使用 https 连接到服务。

最初我试过这个:

            Uri U = new Uri("../Services/Authenticated/VariationsService.svc", 
                               UriKind.Relative);

            string NU = U.AbsoluteUri;

            U = new Uri(NU.Replace("http://", "https://"), UriKind.Absolute);

但它在 U.AbsoluteUri 处失败了,因为它无法在该阶段将相对 Uri 转换为绝对 Uri。那么如何将Uri Scheme改为https呢?

最佳答案

必须先将相对路径转换为绝对路径。我使用正在执行的 Silverlight XAP 文件的 URI 来做到这一点。

可能有一些方法可以减少这一点(用 Uris 进行字符串操作感觉不对)但这是一个开始:

    // Get the executing XAP Uri
    var appUri = App.Current.Host.Source;

    // Remove the XAP filename
    var appPath = appUri.AbsolutePath.Substring(0, appUri.AbsolutePath.LastIndexOf('/'));

    // Construct the required absolute path
    var rootPath = string.Format("https://{0}{1}", appUri.DnsSafeHost, appUri.AbsolutePath);

    // Make the relative target Uri absolute (relative to the target Uri)
    var uri = new Uri(new Uri(rootPath), "../Services/Authenticated/VariationsService.svc");

这不包括传输端口号(在其他情况下您可能想要这样做)。就我个人而言,我会将上述代码放在一个辅助方法中,该方法也可以处理端口(以及在运行 localhost 时您想做的任何不同的事情)。

希望这对您有所帮助。

关于c# - 如何强制相对 URI 使用 https?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3684498/

相关文章:

wcf - 来自 wsdl 文件 : Error Schema with target namespace could not be found 的 svcutil

c# - 对如何在 C# 中使用 return 感到困惑

适用于大文件的 Silverlight 高效哈希

silverlight - 从代码获取Windows Phone 7应用程序标题

wpf - 将 XAML Canvas 导入到 Expression Design 中?

c# - CaSTLe Windsor WcfFacility 出现奇怪的组件注册错误

wcf - 是否有使用 MSMQ 的简单 WCF 在线示例?

c# - 在自定义方法中为数组中的元素分配最小值 (array.Min())

c# - 在另一个应用程序中处理按钮单击

C# Entity Framework "An entity object cannot be referenced by multiple instances of IEntityChangeTracker"