我有一个相对 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/