开发者

How do I force a relative URI to use https?

I have a relative URI:

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

The problem is that depending on whether the user has typed https:// or http:// into their web browser to get to the silverlight开发者_StackOverflow中文版 application, it may use either http or https when trying to contact the service.

I want to force the program to use https for connecting to the service eitherway.

Initially I tried this:

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

            string NU = U.AbsoluteUri;

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

But it fails at U.AbsoluteUri because it can't convert the relative Uri into an absolute Uri at that stage. So how do I change the Uri Scheme to https?


The relative path has to be converted to absolute first. I do that using the Uri of the excuting Silverlight XAP file.

There might be ways to reduce this a bit (it feels wrong doing string operations with Uris) but it's a start:

    // 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");

This does not include transferring a portnumber (which you might want to do in other circumstance). Personally I would put the above code in a helper method that also handles the port (and whatever you want to do differently when running localhost).

Hope this helps.


Instead, you should change your ASPX file which hosts your silverlight, and force user to redirect to SSL only if he/she is logged in using non SSL url. Because ideally it would be perfect if silverlight opens connection only to the same domain and scheme it loaded from.


The protocol is a separate component, so I think that you can just put it in front of your relative address:

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


"Scheme" does not have any meaning in a relative URI. You'll have to convert it to an absolute URI at some point to change the scheme.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜