tags:

views:

247

answers:

3

I have a WCF service running in IIS that calls a function in a class library where httpContext is available. How can I dynamically get the web site url, this may also be a virtual directory?

A: 

I'm not too hot on WCF as I'm more used to .Net 2.0, but would this do it?

HttpContext.Current.Request.Url.ToString()

That should give you the url of the calling request. The catch here is that you could possibly have multiple domains or virtual directories pointing to the same service and it will only give you the url the client specified. However if you have multiple entry points, there is no "one" url anyway.

tjmoore
This also assumes the WCF binding is basicHttpBinding or HTTP binding of sorts (eg netTcpBinding does not have a HttpContext).
Russell
+2  A: 

You could create a ServiceHostFactory which launches your service host manually, then store the endpoint address in a static class to be used by your application. Here is a simple example:

(in your myService.svc):

<%
 @ServiceHost
 Service="MyNamespace.MyService" 
 Factory="MyNamespace.MyServiceHostFactory"
  %>

(in your MyServiceHostFactory.cs):

/// <summary>
/// Extends ServiceHostFactory to allow ServiceHostFactory to be used.
/// </summary>
public class MyServiceHostFactory : ServiceHostFactory
{
    /// <summary>
    /// Creates a new ServiceHost using the specified service and base addresses.
    /// </summary>
    /// <param name="serviceType"></param>
    /// <param name="baseAddresses"></param>
    /// <returns></returns>
    protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
    {
        ServiceHost host;
        host = new ServiceHost(serviceType, baseAddresses);

        MyGlobalStaticClass.Address = baseAddresses[0]; // assuming you want the first endpoint address.

        return host;
    }

(In your MyGlobalStaticClass.cs):

  public static string Address = "";
Russell
+1  A: 

I'm going to start by assuming that you're using HTTP - I'm sure you can adjust the approach depending on what your specific conditions dictate. I tried to get an answer using HttpContext as well and found out that the value was null when running under Cassini so I tried an alternative approach.

System.ServiceModel.OperationContext contains the proper request context. You can follow the request down to the actual request message and scrub the header.

Uri requestUri = System.ServiceModel.OperationContext.Current.RequestContext.RequestMessage.Headers.To;
Ajaxx