January 14, 2016

WCF RIA Service - How to get the hosted server url from within wcf service.

While working on Microsoft LightSwitch Framework with Silverlight client, I encountered a problem, how to find the hosted URL/domain from within WCF RIA Service. Since I am working on local system with application hosted in IIS, and configured my application as virtual directory. So I want to know the address of application's virtual directory.
For example, consider this url:
http://localhost/MyWeb
Where localhost is my host name, and MyWeb is the application's virtual directory alias. There may be more nested pages inside, but we will ignore that, because we only want the url address of virtual directory.
Here is the solution:
We cannot access HttpContext class in silverlight/lightswitch client, so we have to call a proxy function hosted in WCF RIA Service, which will return the current hosted URL to client.
  • HttpContext.Current.Request.Url.Host will give you the host name.
  • HttpContext.Current.Request.ApplicationPath will give you the virtual directory name.
So concatenating these two url string parts will give us the path of virtual directory.
string virtualDirectoryHost = = HttpContext.Current.Request.Url.Host + HttpContext.Current.Request.ApplicationPath;
You might have to add namespace System.Web for HttpContext class or also might have to add reference to System.Web.dll.

No comments:

Post a Comment