2012-07-17 61 views
0

比方说,我们有2个项目与以下布局我怎么能一个IIS环境中编程注册一个WCF服务

  • 工程“网络”
    • Global.asax的(我认为这个目标的登记内例如,void Application_Start(System.Object sender, System.EventArgs e
    • 的web.config
  • 工程 “WCF”
    • DemoService.cs
    • IDemoService.cs

web.config看起来像这样

<configuration> 
    <system.serviceModel> 
     <behaviors> 
      <serviceBehaviors> 
       <behavior name="fooBehavior"> 
        <serviceMetadata httpGetEnabled="true" /> 
       </behavior> 
      </serviceBehaviors> 
     </behaviors> 
     <services> 
      <service name="wcf.DemoService" 
        behaviorConfiguration="fooBehavior"> 
       <endpoint address="mex" 
          binding="mexHttpBinding" 
          contract="IMetadataExchange" /> 
       <endpoint address="" 
          binding="wsHttpBinding" 
          contract="wcf.IDemoService" /> 
      </service> 
     </services> 
    </system.serviceModel> 
</configuration> 

所以...现在...某处(如上面提到我想到global.asax)我需要注册,当浏览到URIwcf.DemoService得到解决和mex-请求wcf.IDemoService得到解决阅读att用来获取WSDL。

这通常通过创建.svc文件来实现,并把标头中的第一行,例如:

<%@ ServiceHost Language="C#" Debug="true" Service="wcf.DemoService" %> 

在例如通过

var serviceHost = new ServiceHost(typeof (wcf.DemoService)); 
serviceHost.Open(); 

并与service元素内的host元素结合这一个控制台应用程序指定URI - 或使用ServiceHost

另一个构造函数过载,但我宁愿去一个静态注册(或任何web.config注册适用于IIS 7.5) - 这可能吗?如果是这样,怎么样?

+0

你想达到什么目的?你的问题的标题看起来与最后一段无关。 – 2012-07-17 13:55:43

+0

@LadislavMrnka不是真的:一个典型的WCF在IIS中的托管是通过使用一个.svc文件(我已经为此添加了一个例子)来实现的,而不是通过a实现托管。svc-file我宁愿去'global.asax'或'web.config'内注册一个_static_(_URI_不能改变,除非例如重新编译 - 与仅移动.svc文件相反)(例如,如果我添加一个'host'元素到'service'元素的一个地址,我会得到一个拒绝访问的异常) – 2012-07-17 14:06:33

+0

.svc文件已经是静态的了,因为你必须和web服务器的管理员能够重命名它如果您是Web服务器的管理员,则可以更改配置文件,有时甚至可以更改global.asax(如果内联)。你可以使用.NET 4.0吗?因为它提供了你想要的,但是.NET 3.5没有。 – 2012-07-17 15:03:17

回答

7

WCF 4(.NET 4.0)提供基于代码的服务注册和基于配置的服务注册。基于

代码的配置由新ServiceRoute通过ASP.NET路由来实现的:

RouteTable.Routes.Add(new ServiceRoute("DemoService", 
          new ServiceHostFactory(), typeof(wcf.DemoService)); 

路由通常与REST服务使用,但它适用于SOAP服务也是如此。

在配置中注册服务称为configuration based activation。您将在web.config中定义虚拟.svc文件:

<serviceHostingEnvironment> 
    <serviceActivation> 
     <add relativeAddress="DemoService.svc" service="wcf.DemoService" /> 
    </serviceActivation> 
</serviceHostingEnvironment> 

在这两种情况下,因为基址总是由IIS中承载您的网站指定要定义你的服务只相对路径。

+0

谢谢,这个很棒!即使它在.NET 4.0之前无法正常工作...... :( – 2012-07-17 18:26:22