WCF服务,如何从一个类库获得网站的网址是什么?类库、网址、网站、WCF

2023-09-03 06:42:23 作者:风透绣罗衣

我在IIS中运行的WCF服务,在一个类库,其中HttpContext的可调用的函数。如何动态获取的网页,这也可能是一个虚拟目录?

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?

推荐答案

您可以创建一个ServiceHostFactory其中手动启动您的服务主机,然后在静态类存储端点地址要使用你的应用程序。下面是一个简单的例子:

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:

(在你的myService.svc):

(in your myService.svc):

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

(在你的MyServiceHostFactory.cs):

(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;
    }

(在你MyGlobalStaticClass.cs):

(In your MyGlobalStaticClass.cs):

  public static string Address = "";