views:

2027

answers:

4

In a Silverlight application I sometimes need to connect to the web site where the application is hosted. To avoid hard coding the web site in my Silverlight application I use code like this:

WebClient webClient = new WebClient();
Uri baseUri = new Uri(webClient.BaseAddress);
UriBuilder uriBuilder = new UriBuilder(baseUri.Scheme, baseUri.Host, baseUri.Port);
// Continue building the URL ...

It feels very clunky to create a WebClient instance just to get access to the URL of the XAP file. Are there any alternatives?

+5  A: 

Application.Current.Host.Source retrieves the URI of the XAP.

Ben M
I assume you mean Application.Current.Host.Source. Anyway, thanks.
Martin Liversage
Yes, sorry--I was referring to the class itself. :-)
Ben M
WARNING: in my experience this doesn't work as expected if you rename your .XAP file to .ZIP (to get around hosting MIME-type restrictions). Just something to be aware of - more info blogged here http://conceptdev.blogspot.com/2009/03/xap-zip-silverlight-gets-confused.html
CraigD
A: 

This will build the root url in ASP.NET. You would then need to pass in baseUrl via Silverlight's InitParams and add "ClientBin\silverlight.xap".

// assemble the root web site path
var baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority + Request.ApplicationPath.TrimEnd ('/') + '/';
scottmarlowe
Your code looks like ASP.NET server side code. My question is about how to get the base URL in the Silverlight client side application.
Martin Liversage
you're right. I added some clarification. The other suggestion works, but gives you the Silverlight control's url, not the base url of the site. Depends which one you want, and how much parsing you want to do.
scottmarlowe
+3  A: 

I use,

Uri baseUri = new Uri(Application.Current.Host.Source, "/");
// Example results:
//  http://www.example.com:42/
//  or
//  https://www.example.com/

No string parsing needed! You can also use this method to create full Urls, for example,

Uri logoImageUri = new Uri(Application.Current.Host.Source, "/images/logo.jpg");
// Example result:
//  http://www.example.com/images/logo.jpg
theahuramazda
A: 

Hi. In my case, I am not working in the main folder. I am working in h||p://localhost:1234/subfolder. That is no problem while working in Visual Studio IDE. But when moving to the server it fails. The following lines

Application.Current.Host.Source

can be replaced through a public function with result like this:

Public Sub AppPathWeb()
    Res = Application.Current.Host.Source.AbsoluteUri.Substring(0, Application.Current.Host.Source.AbsoluteUri.LastIndexOf("/") + 1)
    Return New Uri(Res) 
End Sub

As Result, I can catch my files like this

MyImage = New Uri(AppPathWeb, "HelloWorld.jpg")

And the result is, that on server the url goes to h||p://mydomain.com/mysubfolder/HelloWorld.jpg"

Good luck

goldengel.ch

Nasenbaer