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?
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;
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 = "";
Currently I am working on WCF REST Service and I have same kind of requirement. I need service Host URL in my one of method. Here below is the different ways to get WCF REST Service Host/URL in class library.
You can use WebOperationContext
class which availables in System.ServiceModel.Web
namespace to getting service url. Please note this class is only for WCF REST Service.
WebOperationContext.Current.IncomingRequest.Headers["host"]
- Gives Service Host Name
WebOperationContext.Current.IncomingRequest.UriTemplateMatch.BaseUri.Host
- Gives Service Host Name
WebOperationContext.Current.IncomingRequest.UriTemplateMatch.BaseUri.AbsoluteUri
- Gives Service Full Url
WebOperationContext.Current.IncomingRequest.UriTemplateMatch.RequestUri.AbsoluteUri
- Gives Service Full Url
You can get more information about WebOperationContext
class on MSDN
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With