c#先进行uri解码_c# – 如何强制相对URI使用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");

这不包括转移portnumber(您可能希望在其他情况下执行此操作).就个人而言,我会将上面的代码放在一个帮助器方法中,该方法也处理端口(以及运行localhost时要做的任何不同的操作).

希望这可以帮助.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值